HashMap实现原理

来源:互联网 发布:手机mac地址不可用 编辑:程序博客网 时间:2024/06/07 07:03

HashMap的整体结构如下

  

  简单来说,HashMap由数组+链表组成的,数组是HashMap的主体,链表则是主要为了解决哈希冲突而存在的,如果定位到的数组位置不含链表(当前entry的next指向null),那么对于查找,添加等操作很快,仅需一次寻址即可;如果定位到的数组包含链表,对于添加操作,其时间复杂度依然为O(1),因为最新的Entry会插入链表头部,只需要简单改变引用链即可,而对于查找操作来讲,此时就需要遍历链表,然后通过key对象的equals方法逐一比对查找。所以,性能考虑,HashMap中的链表出现越少,性能才会越好。

转自:http://www.cnblogs.com/chengxiao/p/6059914.html


所以最终存储位置的确定流程是这样的:

h=hash()怎么计算的?为什么下面例子中(17,“www”)算出的hash=16,存储位置放到table[0]中?

解答:hash()函数实现源码:

    final int hash(Object k) {        int h = hashSeed;        if (0 != h && k instanceof String) {            return sun.misc.Hashing.stringHash32((String) k);        }        h ^= k.hashCode();        // 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);    }

有上述:

hash(16)=1;

hash(17)=0;

public static void main(String[] args){HashMap<Integer, String> hashMap=new HashMap<Integer, String>();hashMap.put(0, "000");hashMap.put(1, "aaa");hashMap.put(2, "bbb");hashMap.put(3, "ccc");hashMap.put(1, "ddd");hashMap.put(16, "qqq");hashMap.put(17, "www");for (Map.Entry<Integer, String> entry:hashMap.entrySet()) {System.out.println(entry.getKey()+" "+entry.getValue());}} 

hash










原创粉丝点击