Java八股文系列二:Map之HashMap

115 阅读8分钟

image

一、HashMap源码分析

1.1 成员变量

    //默认初始容量16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    //最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;

    //负载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //链表长度大于8转红黑树
    static final int TREEIFY_THRESHOLD = 8;

    //红黑树长度小于6转链表
    static final int UNTREEIFY_THRESHOLD = 6;

    //数组长度大于64转红黑树
    static final int MIN_TREEIFY_CAPACITY = 64;
    
    //Node数组
    transient Node<K,V>[] table;
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }

1.2 构造方法

    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

在前三个构造器中都没有为table分配内存空间,也就是说为tabel分配内存空间发生在put操作时。

1.3 put操作

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    
    //将key的hashCode的高16位和低16为进行异或运算,得到的值暂且称为hash
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //如果当前table没有初始化,那么直接扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //计算数组下标位置,如果位置上没有key,那么直接赋值
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {//计算出来的数组下标位置上有key
            Node<K,V> e; K k;
            //如果key相等,那么将value进行覆盖,这里先将e指向当前位置的Node,后续有覆盖操作
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //如果是树节点,则进行红黑树的插入操作
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            //到这里就是链表节点
            else {
                //遍历链表,如果key相等则直接覆盖value;
                //如果链表中没有相等的key则直接将新的node接在链表后面,然后判断是否需要转换成红黑树。
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        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;
                }
            }
            //到了此处,说明发现了相同的key,将value覆盖。
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //判断是否需要扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

put流程: image 注意计算数组下标的方法:(n - 1) & hash,用数组的长度减1按位与hash

1.4 扩容操作

    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            //超过最大值就不扩容了
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //没超过最大值就扩充为原来的2被
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            //遍历老的table
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // 将jdk1.7的头插法改成尾插法
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            //原索引
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            //原索引+oldCap
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        //放到原索引的bucket里
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        //放到原索引+oldCap的bucket里
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

数组容量变为原来的2倍,计算数组下标时不用重新计算hash,只需要看原来的hash值新增的高一位bit是0还是1即可,是0则索引不变,是1则索引变为原索引+oldCap。

1.5 get操作

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

先检查key的hash能否在数组中定位到,如果定位不到则说明没有此key;如果定位到了,则遍历链表或红黑树找到相应的节点。

二、HashMap常见面试问题

2.1 HashMap如何实现的?

  • jdk1.7是采用EntrySet数组实现的,就是说数组的元素存储的是一个EntrySet对象,EntrySet有指向后继节点的指针,所以整体上看是数组+链表实现的,根据key的hash值对数组取模来定位在数组中的位置,如果当前位置的key的hash值和key值都相等,那么直接覆盖掉value;如果当前位置的key的hash值相等而key值却不相等,则通过拉链法解决冲突。
  • jdk1.8是采用数组+链表+红黑树实现,当链表超过一定长度后,链表的缺点将被放大,也就是链表的查找时间长,于是将链表转化为红黑树以减少搜索时间,链表搜索的时间复杂度是O(n),红黑树是O(logn)。

2.2 HashMap的长度为什么是2的幂次方?

  • 计算下标时可以提高效率。计算下标自然想到取余运算,但是发现取余运算当除数是2的幂次等价于与其减1的按位与操作,也就是说当length是2的幂次的时候,hash%length == hash&(length-1),而二进制位操作比取余操作效率要高。
  • 减少哈希冲突。通过源码发现计算数组下标的方法(length - 1) & hash。如果length是2的幂次,那么length-1用二进制表示的话低位全是1,如下图。 image 如果length不是2的幂次,那么length-1就会有0出现,如下图。 image 如果length不是2的幂次,hashCode就有多种可能使index=21,h的低位部分不在具有唯一性了,所以哈希冲突的几率会增大。
  • 在扩容时,元素的新位置要么不变,要么是在原位置的基础上再移动2次幂的位置,这样大大减少了之前已经散列良好的老数据的重新散列,如下图。 image

2.3 HashMap线程不安全体现在哪些方面?

  • jdk1.7时,链表上会出现循环。jdk1.7扩容的关键代码:
    void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry<K,V> e : table) {
            while(null != e) {
                Entry<K,V> next = e.next;//标注【1】
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }

整个流程就是两重循环,先遍历数组,再遍历数组上的链,通过头插法将节点放到正确的位置。 现在假设一个HashMap的容量是2,负载因子是0.75,那么put第二个key的时候会扩容,假设都移动到了3的位置,当两个线程同时put时,线程2在标注【1】的地方被挂起,线程1完成了扩容,此时的情况如下图。 image

此时线程2恢复,继续执行后续步骤,结果如下图:

    if (rehash) {
        e.hash = null == e.key ? 0 : hash(e.key);
    }
    int i = indexFor(e.hash, newCapacity);
    e.next = newTable[i];
    newTable[i] = e;
    e = next;

image

执行后,变量e指向节点b,因为e不是null,则继续执行循环体,执行后的引用关系: image

变量e又重新指回节点a,只能继续执行循环体,这里仔细分析下:

  1. 执行完Entry<K,V> next = e.next;,目前节点a没有next,所以变量next指向null;
  2. e.next = newTable[i]; newTable[i]指向b,也就是说a的next指向了b节点,此时b指向a,a指向b,形成了循环;
  3. newTable[i] = e; 节点a放入了数组i位置;
  4. e = next; e指向了null。

最终的引用关系: image

假设c是一个新的key,根据c的hash计算出数组下标也在3这个位置上,但是这个map中没有c这个key,那么当get(c)时,就会陷入b和a的死循环中。

  • jdk1.8在扩容时将头插法变成了尾插法,理论上不会出现死循环的问题,但是会存在丢失数据的问题。

    jdk1.8 putVal方法:

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //如果当前table没有初始化,那么直接扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //计算数组下标位置,如果位置上没有key,那么直接赋值
        if ((p = tab[i = (n - 1) & hash]) == null) //标注【2】
            tab[i] = newNode(hash, key, value, null);
        //省略
    }

假设线程1执行完标注【2】结果为true并在此处挂起,线程2在tab[i]处插入了新的节点,此时线程1恢复继续执行,会在tab[i]处更新成自己的节点数据,线程2的数据被覆盖了。

2.4 既然HashMap线程不安全,那有线程安全的Map吗?

有,ConcurrentHashMap,Hashtable

2.5 HashMap默认负载因子为什么是0.75?

经过大量的测试,测出0.75是性能最好的。既有较高的空间利用率,又减少了哈希冲突。

2.6 数组+数组的结构可以实现HashMap吗?

也可以,就是性能不好。数组列来存放不同的hash的key,行来解决哈希冲突,数组的行不能太小,太小要频繁扩容,也不能太大,太大的话就浪费空间。

三、总结

  • 为了避免频繁扩容,最好在初始化HashMap时指定大小。
  • HashMap不是线程安全的,多线程情况下会出现循环链表,数据丢失的情况。
  • jdk1.8引入了红黑树,当链表达到一定长度时转化为红黑树,以减少搜索时间。
  • HashMap的Key值不重复,key和value允许为null。