我正在制作一个电子表格应用程序,我正在使用 HashMap 将数据存储在单元格中。作为键,我使用的是 Point 类,它只有行数和列数。我遇到的问题是,如果我将 HashMap.get() 与新点一起使用,它会返回空值。
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("\t");
if (j == maxRow)
System.out.println("");
}
}
返回:
null null
null null
我可能遗漏了一些明显的东西,但我自己找不到。另外,如果您碰巧知道是否有更好的数据结构来存储来自单元格的数据,我很想听听。 提前致谢!
最佳答案
为了详细说明我上面的评论,您的 Point 类应该实现 hashcode 和 equals,如下所示:
(存在许多实现,它只是一个有效的实现)
假设您的实例的变量是 x
和 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;
}
否则,如果您不覆盖这些方法,Object
的 Javadoc 会很好地解释您的问题:
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();
因此,new Point(1,2)
不会被视为等于 new Point(1,2)
,因此永远无法从您的 map
。
关于当我创建对象的新实例作为键时,Java HashMap.get() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20307443/