您的位置:首页 > 编程语言 > Java开发

Java HashCode 详解

2016-04-03 09:32 399 查看
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)));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: