JDK7与JDK8中HashMap的比较

    xiaoxiao2021-03-26  9

    在开始比较之前,还是老办法,我们对HashMap基本的知识做一个简单梳理和总结,然后在这个基础之上,对JDK8中HashMap的实现进行比较就比较的容易了: 1、HashMap是非线程安全的; 2、HashMap的get()方法来获取获取map中的对象,当get(key)为空的时,map返回的object为null;put()方法将对应的对象放入的HashMap的桶子中;也是HashMap中比较常用的方法; 3、HashMap的负载因子为0.75,如果HashMap的大小超出了定义的容量,那么HashMap将会和其他的集合类一样创建原来两倍大的HashMap的bucket数组来重新调整新的HashMap。 4、HashMap的初始大小为16,负载因子为0.75,增加的大小为2的次幂。

    JDK7中的HashMap

    在这个版本的JDK中,HashMap是维护一个数组,数组中的每一项都是一个Entry中的: transient Entry[] table; 而Map中的key,value则以Entry的形式存放在数组中: static class Entry<K,V> implements Map.Entry<K,V> { final K key; V value; Entry<K,V> next; int hash; 。。。 。。。 } 而这个Entry应该放在数组的哪一个位置上(这个位置通常称为位桶或者hash桶,即hash值相同的Entry会放在同一位置,用链表相连),是通过key的hashCode来计算的。 final int hash(Object k) { int h = hashSeed; if (0 != h && k instanceof String) { return sun.misc.Hashing.stringHash32((String) k); } h ^= k.hashCode(); h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); } 通过hash计算出来的值将会使用indexFor方法找到它应该所在的table下标: static int indexFor(int h, int length) { return h & (length-1); } 也就是我们在put的时候: map.put(id, name); 是将创建的map对象放到Entry数组中,具体的put方法如下: public V put(K key, V value) { if (key == null) return putForNullKey(value); int hash = hash(key.hashCode()); int i = indexFor(hash, table.length); for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null; } //这里值得注意的是,当Key为null的时候,put的value值会被放置到table[0]中 private V putForNullKey(V value) { for (Entry<K,V> e = table[0]; e != null; e = e.next) { if (e.key == null) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(0, null, value, 0); return null; } 当两个key通过hashCode计算相同时,则发生了hash冲突(碰撞),HashMap解决hash冲突的方式是用链表。当发生hash冲突时,则将存放在数组中的Entry设置为新值的next(这里要注意的是,比如A和B都hash后都映射到下标i中,之前已经有A了,当map.put(B)时,将B放到下标i中,A则为B的next,所以新值存放在数组中,旧值在新值的链表上)。 在上面的HashMap总结中我们知道HashMap的负载因子为0.75,如果HashMap的大小超出了定义的容量,那么HashMap将会和其他的集合类一样创建原来两倍大的HashMap的bucket数组来重新调整新的HashMap。那么他具体是怎么实现的呢?在HashMap中有这个样一个方法:addEntry(),在上面的put方法中也能看到: void addEntry(int hash, K key, V value, int bucketIndex) { if ((size >= threshold) && (null != table[bucketIndex])) { resize(2 * table.length); hash = (null != key) ? hash(key) : 0; bucketIndex = indexFor(hash, table.length); } createEntry(hash, key, value, bucketIndex); } void createEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<>(hash, key, value, e); size++; } 而addEntry()对当size大于threshold时,会发生扩容。 threshold等于capacity*load factor。jdk7中resize,只有当 size>=threshold并且 table中的那个槽中已经有Entry时,才会发生resize。即有可能虽然size>=threshold,但是必须等到每个槽都至少有一个Entry时,才会扩容。还有注意每次resize都会扩大一倍容量。

    然后我们在来看看这个HashMap的个方法:

    public V get(Object key) { if (key == null) return getForNullKey(); Entry<K,V> entry = getEntry(key); return null == entry ? null : entry.getValue(); } private V getForNullKey() { if (size == 0) { return null; } for (Entry<K,V> e = table[0]; e != null; e = e.next) { if (e.key == null) return e.value; } return null; } 在上面的代码可看出:HashMap的get(Object key)方法来获取获取map中的对象,当get(key)为空的时,map返回的object为null。

    JDK8中的HashMap

    在JDK7中通过对以上HashMap的了解我们知道,要是在创建Map的时候出现大量的key相同,也就是成百上千个节点在hash时发生碰撞时候,存储一个链表中,那么如果要查找其中一个节点,那就不可避免的花费O(N)的查找时间,这将是多么大的性能损失。这个问题终于在JDK8中得到了解决。再最坏的情况下,链表查找的时间复杂度为O(n),而红黑树一直是O(logn),这样会提高HashMap的效率。而这就JDK8对HashMap的优化。 JDK7中HashMap采用的是位桶+链表的方式,即我们常说的散列链表的方式,而JDK8中采用的是位桶+链表/红黑树的方式,也是非线程安全的。当某个位桶的链表的长度达到某个阀值的时候,这个链表就将转换成红黑树。JDK8中,当同一个hash值的节点数不小于8时,将不再以单链表的形式存储了,会被调整成一颗红黑树(上图中null节点没画)。这就是JDK7与JDK8中HashMap实现的最大区别。

    JDK中Entry的名字变成了Node,原因是和红黑树的实现TreeNode相关联:

    transient Node<K,V>[] table;

    当冲突节点数不小于8-1时,转换成红黑树:

    static final int TREEIFY_THRESHOLD = 8;

    所以put方法会有很大的改变:

    /** * put方法 */ public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; //如果当前map中无数据,执行resize方法。并且返回n if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; //如果要插入的键值对要存放的这个位置刚好没有元素,那么把他封装成Node对象,放在这个位置上就完事了 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); //否则的话,说明这上面有元素 else { Node<K,V> e; K k; //如果这个元素的key与要插入的一样,那么就替换一下,也完事。 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; //1.如果当前节点是TreeNode类型的数据,执行putTreeVal方法 else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { //还是遍历这条链子上的数据,跟jdk7没什么区别 for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); //2.完成了操作后多做了一件事情,判断,并且可能执行treeifyBin方法 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) //true || -- e.value = value; //3. afterNodeAccess(e); return oldValue; } } ++modCount; //判断阈值,决定是否扩容 if (++size > threshold) resize(); //4. afterNodeInsertion(evict); return null; }

    treeifyBin()将链表转换成红黑树。

    final void treeifyBin(Node<K,V>[] tab, int hash) { int n, index; Node<K,V> e; if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize(); else if ((e = tab[index = (n - 1) & hash]) != null) { TreeNode<K,V> hd = null, tl = null; do { TreeNode<K,V> p = replacementTreeNode(e, null); if (tl == null) hd = p; else { p.prev = tl; tl.next = p; } tl = p; } while ((e = e.next) != null); if ((tab[index] = hd) != null) hd.treeify(tab); } }
    总结:通过比较,我们看出HashMap还是非线程安全的,基本的值和属性没有发生变化,变化最大就是HashMap的实现方式的改变,由原来的JDK7中HashMap采用的是位桶+链表的方式,即我们常说的散列链表的方式,而JDK8中采用的是位桶+链表/红黑树的方式,这样做的好处也在上面说的很清楚了。 文章参考来源:(http://www.importnew.com/23164.html 向大神致敬)
    转载请注明原文地址: https://ju.6miu.com/read-600369.html

    最新回复(0)