Java HashMap.get() returns null when I create a new instance of an object as a key(当我创建对象的新实例作为键时,Java HashMap.get() 返回 null)
问题描述
I'm making a spreadsheet application and I'm using a HashMap to store the data in the cells. As the key I'm using a Point class, which only has the number of rows and colums. The problem I'm having is that if I use the HashMap.get() with a new Point, it returns a null value.
HashMap<Point, String> cache = new HashMap<Point, String>();
Point p1 = new Point(1,1);
Point p2 = new Point(2,2);
cache.put(p1, "Test: 1,1");
cache.put(p2, "Test: 2,2");
int maxRow = 2;
int maxCol = 2;
for (int i = 1; i <= maxRow; i++) {
for (int j = 1; j <= maxCol; j++) {
System.out.print(cache.get(new Point(i,j)));
if (j < maxCol)
System.out.print(" ");
if (j == maxRow)
System.out.println("");
}
}
This returns:
null null
null null
I'm probably missing something obvious, but I can't find it myself. Also, if you happen to know if there is a better data structure for storing data from cells I'd love to hear it. Thanks in advance!
To detail my comment above, your Point class should implement hashcode and equals like following:
(many implementations exist, it's just one that works)
Supposing that your instance's variables are x
and y
.
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
if (x != point.x) return false;
if (y != point.y) return false;
return true;
}
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
Otherwise, if you don't override those methods, Object
's Javadoc explains well your issue:
As much as is reasonably practical, the hashCode method defined by
* class {@code Object} does return distinct integers for distinct
* objects. (This is typically implemented by converting the internal
* address of the object into an integer, but this implementation
* technique is not required by the
* Java<font size="-2"><sup>TM</sup></font> programming language.)
*
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.System#identityHashCode
*/
public native int hashCode();
Thus, new Point(1,2)
would not be considered as equal to new Point(1,2)
and therefore, could never be retrieved from your Map
.
这篇关于当我创建对象的新实例作为键时,Java HashMap.get() 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当我创建对象的新实例作为键时,Java HashMap.get
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01