在HashMap中,在get和put(可能还有其他地方,没记那么多)的时候都对key的hashCode进行hash,返回一个hash然后进行添加或者get。具体是这样的:
int hash = hash(key.hashCode());然后hash函数的实现是这样:/**
     * Applies a supplemental hash function to a given hashCode, which
     * defends against poor quality hash functions.  This is critical
     * because HashMap uses power-of-two length hash tables, that
     * otherwise encounter collisions for hashCodes that do not differ
     * in lower bits. Note: Null keys always map to hash 0, thus index 0.
     */
    static int hash(int h) {
        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }我把注释也贴出来了,因为就是看不懂注释,那些注释具体的是啥,英语实在太烂了。能举个例子说说最好了。

解决方案 »

  1.   


            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;
            }
    从这段代码我觉得这个是用来确定位置的,那个注释也是差不多确定位置的意思。因为HashMap里面有一个table(就是HashMap里面的Entry数组(Entry就是一个映射,里面有一个key和一个alue,HashMap的主要功能就是通过Entry来实现的)),在这个数组里面要确定你要取的是哪一个Entry就要调用indexFor()这个方法,这个方法的一个参数就是通过hash()函数来确定的。具体是怎么用的就不多说了,说起来要研究好久,不知道楼主明白了没?
      

  2.   

    你说的我明白了,我说的你没明白。我想知道那个hash函数那么写的意义
      

  3.   

    哦,我是想说这个函数的意义就是用来确定要取的entry在entry数组中的位置的,至于它为什么这么那我就不知道了,望后面的大牛来指点……
      

  4.   

    就是为了纠正hashcode函数的缺陷,因为hashmap的capacity的值是2的指数个,如果两个对象的hashCode值的低位相同,很有可能导致hashCode/capacity的值相同,就会出现冲突。
    0101 0000 0000 1111 = 20495
    0111 0000 0000 1111 = 28687
    假如hashmap的capacity是16,那么20495%16 = 15,28687%16=15,就冲突了
      

  5.   

    hashmap数据的存储就是按照hashcode来的,相同hashcode的数据是放在链的同一位置
      

  6.   

    hashmap 应该是先用对象的hash值去找对象,找到的值是个数组即具有相同的hash值的,然后再用equal方法去比较二个是否相等,相等的则返回
      

  7.   

    是的,但是设计者重新给出这个hash函数处理hashCode后使得它们分布更加好了(以前版本的hash函数不是这样的),比较想从数学上知道为何更加好了