JAVA JDK7和JDK8中HashMap的实现

来源:互联网 发布:护卫神linux 编辑:程序博客网 时间:2024/06/05 06:46

JDK7中的HashMap

HashMap底层维护着一个数组,数组中的每一项都是一个Entry

transient Entry<K,V>[] table;

存入HashMap的键值对key-value以Entry对象的形式都存储在该table数组中

static class Entry<K,V> implements Map.Entry<K,V> {        final K key;        V value;        Entry<K,V> next;        int hash; }

Entry放在数组的位置称为位桶或者Hash桶,原因是相同Hash码的对象会放在同一位置,使用链表相连,该hashcode是通过key来计算的

final int hash(Object k) {    int h = 0;    h ^= k.hashCode();    h ^= (h >>> 20) ^ (h >>> 12);    return h ^ (h >>> 7) ^ (h >>> 4);}

通过hash计算出来的值会使用indexFor方法找到对应的table下标
[通过计算hashcode和数组下标最大值的与运算 – 相当于用hashcode对table.length取模]

static int indexFor(int h, int length) {    return h & (length-1);}

当两个key的hashCode相同时,就产生了哈希冲突,HashMap解决哈希冲突使用链表法。

当产生哈希冲突时,把存放在数组中的Entry的值设置为新值的next.

所以当哈希冲突很多时,HashMap退化成链表

总结插入元素的过程:

当向HashMap中put一对key-value时,会先根据key的hashCode计算出在table数组中存放的位置,如果该位置没有对象存在,就直接把该对象放进数组中;如果已经有对象存在,先顺着该对象的链开始查找[因为不允许存在相同的key],如果存在相同的key,就更新value值;否则将新对象插入到链表尾部。

ps:注意,key为null时,都放到table[0]中(HashMap的key,value都可以为null)

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;}

当size大于threshold时会产生扩容,threshold = capacity * loadfactor = 0.75*16

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);}

JDK7中扩容,只有当size>=threshold且要插入table的位置中已经存在对象才会发生扩容。且每次扩大到(当前长度+1)*2,即扩大当前容量的一倍

JDK8中的HashMap

一直到JDK7,HashMap的结构都是基于一个数组和多个链表来实现的,哈希冲突的时候就以链表的形式存储。

这样可能存在的问题是如果有很多节点发生碰撞的话,存储在一个链表中,如果要查找其中一个节点,就不可避免的花费O(N)的查找事件。这是很大的性能损失。

因此在JDK8中采用的是位桶+链表/红黑树的方式,也是非线程安全的。当某个位桶的链表长度达到某个阈值的时候,就会转换成红黑树

这里写图片描述

JDK8中当同一个哈希值的节点数大于等于8时,就会被调整成一颗红黑树。

Entry的名字编程了Node

transient Node<K,V>[] table;

阈值是8

static final int TREEIFY_THRESHOLD = 8;

插入的方法也有很大的变化

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;    }

indexFor方法也被删除,直接使用(tab.length-1)&hash

static final int hash(Object key) {  int h;    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);}