홈>
equals와 hashcode ()가 제대로 구현되도록하려면 다음 규칙을 확인해야합니다
- 반사율
- 대칭
- 전이성
- 일관성
- 무치 개성
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));
}
}
-
답변 # 1
HashSet
멤버의 속성을 변경할 수 없습니다 (equals
의 구현에 참여하는 또는hashCode
) 작동 할 것으로 예상합니다.이러한 속성을 변경하지 말고
대안으로, 당신이 당신의HashSet
에서 요소를 제거하십시오. 변경하기 전에 나중에 다시 추가하십시오.Point
에 독특한 불변 속성을 가지고 있다면 수업, 당신은 그것을HashMap
의 열쇠로 사용할 수 있습니다 (예 :HashMap<Integer,Point>
) 그리고 당신은 당신의Point
가 필요하지 않습니다equals
를 재정의하는 클래스 그리고hashCode
.