![](/img/trans.png)
[英]Java how does HashMap identify the key object if hashCode are the same and equals is true?
[英]How does HashMap in Java use equals() and hashCode() to find objects?
我已經定義了一個Point類,如下所示,覆蓋了equals()
和hashCode()
。 我期待在main()
方法中,“Key Found”將被打印,但事實並非如此。
據我所知,Java使用equals()
和hashCode()
在HashMap
添加或查找對象。 我不確定我在這里做錯了什么。
import java.util.*;
public class Point {
int row = 0;
int col = 0;
public Point(int row, int col) {
this.row = row;
this.col = col;
}
public String toString() {
return String.format("[%d, %d]", row, col);
}
public boolean equals(Point p) {
return (this.row == p.row && this.col == p.col);
}
public int hashCode() {
return 31 * this.row + this.col;
}
public static void main(String[] args) {
HashMap<Point, Integer> memo = new HashMap<>();
Point x = new Point(1, 2);
Point y = new Point(1, 2);
memo.put(x, 1);
if (x.equals(y))
System.out.println("x and y are equal");
System.out.println("Hashcode x= " + x.hashCode() + " Hashcode y= " +
y.hashCode());
if (memo.containsKey(y)) {
System.out.println("Key found");
}
}
}
output
x and y are equal
Hashcode x= 33 Hashcode y= 33
問題是你實際上沒有覆蓋equals()
方法。 您嘗試覆蓋的equals()
方法將Object
作為參數,而不是Point
對象。 因此,實際上不會調用您實現的equals()
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.