关于hashcode的一点理解

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()函数的使用:
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的存取效率。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值