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
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01