java 일반 객체에 Set으로 추가할 때, 특정 필드로 유일성을 보장하려면 hashCode()를 구현해야 한다. (참고로 Comparator(isEqual), compare() 메소드는 sorting 용이다.)


public class Up { private id; // setter, getter public int hashCode() {
return Long.hashCode(id);
} }



테스트 코드


Up up = new Up();
up.id = 1;
Up up2 = new Up();
up2.id = 1;

Set set = Sets.newHashSet();
set.add(up);
set.add(up2);

System.out.println(set);


up 객체에 hashcode() 를 상속/구현하지 않으면 set의 크기는 2가 된다.

Up[id=1..], Up[id=1..]



up 객체에 hashcode()를 추가하면, set의 크기는 1이다.

Up[id=1..]


* HashSet 구현 참조

add 할 때, 객체의 hash 코드를 참조한다.

public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}


Posted by '김용환'
,