Tan*_*anM 4 java equals hashmap
我已经定义了一个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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |