首先說建議的情況: 比如你的對象想放到Set集合或者是想作為Map的key時(非散列的Set和Map,例如TreeSet,TreeMap等),那麼你必須重寫equals()方法,這樣才能保證唯一性。當然,在這種情況下,你不想重寫hashCode()方法,也沒有錯。但是,對于良好的程式設計風格而言,你應該在重寫equals()方法的同時,也重寫hashCode()方法。
然後再說說必須重寫hashCode()的情況:
如果你的對象想放進散列存儲的集合中(比如:HashSet,LinkedHashSet)或者想作為散列Map(例如:HashMap,LinkedHashMap等等)的Key時,在重寫equals()方法的同時,必須重寫hashCode()方法。
在Set裡如果保證其中元素的唯一型:
Set的一個實作HashSet中的add方法,HashSet内部使用一個HashMap來存放對象,
HashSet把要儲存的對象做為其内部HashMap的key,如下:
//PRESENT為一個輔助的Object型對象
public boolean add(E o) {
return map.put(o, PRESENT)==null;
}
如果有兩個對象A,B, A.equals(B)傳回ture,則
A和B隻會有一個被儲存在set中。
在HashMap中判斷兩個key相同的邏輯是 hashcode()相等并且 equals()傳回true。
再看看HashMap中的put()
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry e = table[i]; e != null; e = e.next) {
Object k;
/**
* 因為A.equals(B)為true,故A.hashCode() == B.hashCode();
* 故會進入到下面的if塊内部,進而保證了A和B隻有一個被儲存在Set裡
*/
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) 中,隻有hashcode相等時
才會調用後面的key.equals(k)