1:
HashCode 存在主要是爲了配合基於散列的集合一起使用,例如,hashMaP,hashSet,hashTable 等
2:
HashCode設計時最重要的原則之一就是同一個對象一定要產生相同的hashCode
3:
重載equals 時要考慮 重載 hashCode 方法,這時候要特別留心
因爲 在 基於散列的集合中操作是基於 hashCode 判斷相等與否的,如果hashCode 不一樣,及時equals 重載 之後認爲其相等也無濟於事。
比如 代碼片段如下:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
package basic;
/*
* @author: wjf
* @version: 2016年4月3日 上午9:07:45
*/
import java.util.HashMap;
import java.util.Map;
public class TestHashCode {
private int a;
public TestHashCode(int a){
this.a=a;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public boolean tequal(TestHashCode obj){
return this.a == obj.getA();
}
/*
* 在設計hashCode 和 equals 方法是,最好不要依賴於易變對象,否則,如果使用類似hashMap 等數結構時,如果對象發生了變化
* 可能找不到該對象了。
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result +a;
return result;
}
@Override
// 非常好的 equals 標準寫法,千萬不要直接判斷 this.XX==obj.XX可能拋出異常
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TestHashCode other = (TestHashCode) obj;
if (a != other.a){
System.out.println("test");
return false;
}
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestHashCode t1=new TestHashCode(1);
System.out.println(t1.hashCode());
t1.setA(1);
System.out.println(t1.hashCode());
Map<TestHashCode, Integer> map=new HashMap<TestHashCode,Integer>();
map.put(t1, 2);
System.out.println(map.get(new TestHashCode(1)));
}
}