【发布时间】:2017-12-14 11:12:44
【问题描述】:
为了确保我们的 equals 和 hashcode() 得到很好的实现,我们必须确保以下规则
- 自反性
- 对称
- 传递性
- 一致性
- 非无效性
但是我的以下实现违反了规则一致性(如果我修改它的字段,x 永远不会等于它自己)所以我必须做些什么才能使这个测试正确运行?
public class TestHashCode {
public class Point {
public int x;
public int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int hashCode() {
int hash = 3;
hash = 97 * hash + this.x;
hash = 97 * hash + this.y;
return hash;
}
public boolean equals(Object obj) {
// generated code by netbeans IDE
}
}
@Test
public void testEquals() {
Point x = new Point(1, 1);
Set<Point> pointsAsSet = new HashSet<>();
pointsAsSet.add(x);
x.x = 3 ;
Assert.assertTrue(pointsAsSet.contains(x));
}
}
【问题讨论】: