我已经定义了一个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 …Run Code Online (Sandbox Code Playgroud)