转载请注明出处:http://blog.youkuaiyun.com/anxpp/article/details/51234835,谢谢!
我们知道,使用散列的容器,其高性能的主要影响因素之一就是hash值。
在HashMap中,为了更好的性能,我们希望作为Key的对象提供一个合理的hash函数以便能将其合理的分配到桶中。
而在实际的HashMap中,对从对象获取的hash值又做了调整。
我们先看源码:
- static final int hash(Object key) {
- int h;
- return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
- }
我们可以将其详细步骤等价改为如下:
- static final int hash(Object key) {
- if(key == null)
- return 0;
- int h = key.hashCode();
- int temp = h >>> 16;
- int newHash = h ^ temp;
- return newHash;
- }