我正在使用 coder pad 来执行此操作,即使在重写 hashCode 和 equals 后,结果似乎仍显示重复项。感谢您的帮助!
public static class Point{//just a class
int x, y;
Point(int x, int y){
this.x = x;
this.y = y;
}
// @Override
public int hashCode(){//17 and 31 from effective java
int result = 17;
result = 31 * result + x;
result = 31 * result + y;
return result;
}
// @Override
public boolean equals(Point p){
return p.x == x && p.y == y;
}
}
public static void main(String[] args) {//main func
Set<Point> res = new HashSet<>();
res.add(new Point(100, 0));
res.add(new Point(100, 0));
for (Point a: res){
System.out.println(a.x + " " + a.y);
}
最佳答案
你没有重写 equals,而是重载了 equals,这不会完成任务。
您的 equals
方法必须采用一个 Object 参数,然后进行适当的转换。你必须写一些类似的东西
public boolean equals(Object o) {
if (o instanceof Point) {
Point p = (Point) o;
return x==p.x && y==p.y;
}
return false;
}
关于java - hashcode 和 equals 重写不起作用,出了什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43358835/