hashcode()是java.lang.Object的一个函数,它的主要被使用在对Collection中对象的存取中。
java.lang.Object中对hashcode()方法的描述是这样的:
[quote]
The general contract of hashCode is:
I: Whenever it is invoked on the same object more than once during
an execution of a Java application, the hashCode method
must consistently return the same integer, provided no information
used in equals comparisons on the object is modified.
This integer need not remain consistent from one execution of an
application to another execution of the same application.
II: If two objects are equal according to the equals(Object)
method, then calling the hashCode method on each of
the two objects must produce the same integer result.
III: It is *not* required that if two objects are unequal
according to the java.lang.Object#equals(java.lang.Object)
method, then calling the hashCode method on each of the
two objects must produce distinct integer results. However, the
programmer should be aware that producing distinct integer results
for unequal objects may improve the performance of hashtables.
[/quote]
再来看看java.util.HashMap 中 存取对象时对hashcode()函数的使用:
由此看来如果一个class的hashcode函数效果不够好,就可能使得hashMap的链表数组中的某个链表非常长,从而影响了hashMap的存取效率。
java.lang.Object中对hashcode()方法的描述是这样的:
[quote]
The general contract of hashCode is:
I: Whenever it is invoked on the same object more than once during
an execution of a Java application, the hashCode method
must consistently return the same integer, provided no information
used in equals comparisons on the object is modified.
This integer need not remain consistent from one execution of an
application to another execution of the same application.
II: If two objects are equal according to the equals(Object)
method, then calling the hashCode method on each of
the two objects must produce the same integer result.
III: It is *not* required that if two objects are unequal
according to the java.lang.Object#equals(java.lang.Object)
method, then calling the hashCode method on each of the
two objects must produce distinct integer results. However, the
programmer should be aware that producing distinct integer results
for unequal objects may improve the performance of hashtables.
[/quote]
再来看看java.util.HashMap 中 存取对象时对hashcode()函数的使用:
public V get(Object key) {
if (key == null)
return getForNullKey();
//对key的hash码进行映射
int hash = hash(key.hashCode());
/**
*把得到的hash码处理成0到table.length之间的值,做为查找对象的index,沿着
*这条链表查找该key对应的对象(hashMap 中使用链表数组储存对象)。
*e.hash与该key的hash码相等的Entry对象中的value被返回。
*/
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}
由此看来如果一个class的hashcode函数效果不够好,就可能使得hashMap的链表数组中的某个链表非常长,从而影响了hashMap的存取效率。