[英]Java HashMap.get() returns null when I create a new instance of an object as a key
我正在制作電子表格應用程序,並且正在使用HashMap將數據存儲在單元格中。 作為關鍵,我使用的是Point類,該類僅具有行數和列數。 我遇到的問題是,如果我將HashMap.get()與新的Point一起使用,它將返回一個空值。
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
的equals方法使用==
即對象身份。 由於Hashmap使用equals方法,因此最終使用==
比較鍵,除非它是同一對象,否則將返回false。
要解決此問題,請實施Point的equals
和hashCode
方法,以便如果坐標相同,則point1.equals(point2)
返回true。
為了在上面詳細說明我的評論,您的Point類應該實現哈希碼,並且應如下所示:(存在許多實現,這只是一個可行的實現)假設實例的變量為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
檢索到。
由於使用Point作為哈希圖的鍵,因此您需要覆蓋默認的equals和hashCode方法
@Override
public boolean equals(Object obj){
if (obj == null)
return false;
if (obj == this)
return true;
if (!(obj instanceof Point.class))
return false;
Point point = (Point) obj;
return this.x == point.x && this.y == point.y;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.