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


基础教程推荐
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 从 python 访问 JVM 2022-01-01