HashMap源码分析(JDK1.8)

481 阅读9分钟

1. 介绍

HashMap:作为Map的主要实现类,线程不安全,因此在多线程的环境下可能会有问题,效率高,key\value可以为null,底层基于散列算法实现

本文基于JDK1.8来分析HashMap的源码,我们知道,JDK1.7的HashMap底层使用的是数组+链表,相比于JDk1.7,JDK1.8引入了红黑树来优化链表解决过长链表效率低的问题,以及重写 resize 方法,移除了 alternative hashing 相关方法,避免重新计算键的 hash 等。

2. 原理

HashMap底层是基于拉链式的散列算法来实现的,由数组+链表组成,1.8后又增加了红黑树,HashMap在进行增删查操作时,首先会通过元素的hash值%HashMap长度,得到桶的下标,定位到元素所在的桶位置,然后再从链表中定位到元素。

当HashMap数组的某一个索引位置上的链表形式的数据个数 > 8 且当前数组的长度 > 64,此时该索引位置上的所有数据会改为红黑树存储

在new HashMap()实例化后,底层创建了一个 transient Node<K,V>[] table 数组,在JDk1.8中HashMap实例化的时候并不会初始化长度,而是首次调用put方法时底层才创建长度为16的数组。

3. 源码分析

首先介绍一下HashMap源码中的一些常见变量

  • DEFAULT_INITIAL_CAPACITY:HashMap的默认容量,16
  • MAXIMUM_CAPCITY:HashMap的最大支持容量,2^30
  • TREEIFY_THRESHOLD:BUcket桶中链表长度大于该默认值,转化为红黑树
  • UNTREEIFY——THRESHOLD:BUCKET中红黑树存储的NODE小于该默认值,转化为链表
  • MIN_TREEIFY_CAPACITY:桶中NODE被书画时最小的hash表容量
  • table:存储元素的数组,总是2的n次幂
  • entrySet:存储具体元素的集
  • size:hashMap中存储的键值对的数量
  • modCount:HashMap扩容和结构改变的次数。
  • threshold:扩容的临界值,=容量*填充因子 当HashMap的size超过这个值是会进行扩容操作
  • loadFactor:填充因子(负载因子)

3.1 构造方法

首先我们来看一下HashMap的构造方法

/**
将填充因子变量设置为默认的0.75,我们比较常用的
**/
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

/**
会调用构造3
**/
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}


/**
会将另一个 Map 中的映射拷贝一份到自己的存储结构中来
**/
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(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

3.2 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;
    //判断是否为第一次put,初始化桶数组table
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
     //如果桶中不包含键值对节点引用,则将新键值对节点的引用存入桶中即可,(n - 1) & hash等价于对length 取余,定位到key在桶数组的位置。
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        //如果key的值以及节点的hash值与链表中的第一个键值对节点相等时,则将e指向该键值对
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
            //如果桶中的引用类型为树,则直接调用红黑树的put方法插入
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            //对链表进行遍历,并统计到链表的长度
            for (int binCount = 0; ; ++binCount) {
                //如果链表中不包含要插入的key-value时,则将该Node节点接在链表的最后面
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    //如果链表的长度大于或者等于树化的阈值,则该链表会转换为红黑树
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                //判断链表是否包含要插入的key/value,true则直接break
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        //判断要插入的键值对是否存在hashmap中
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    //如果hashMap存储的键值对的数量大于扩容的临界值,则会进行扩容操作
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

当桶数组的table为空的时候,会先调用resize()扩容方法进行初始化,如果桶中该键值对引用的节点为空时,则直接将该键值对存入桶中。

如果该节点上有数据,则会接着进行判断,当该节点的hash值和添加的key的hash值相同,并且该节点的第一个key与添加的key相等时则直接指向该键值对。

如果桶的引用类型为Tree树时,则会直接调用红黑树的put方法进行插入操作,如果都不成立的话,则会对链表进行遍历,来查找链表中是否包含插入的key-value,不包含的话直接插入在该链表的最后面,如果插入后链表的长度大于TREEIFY_THRESHOLD的话,则会将该链表转换为红黑树,最后,如果更新后的hashMap的size大于扩容的临界值时,则会进行扩容操作

3.3 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) {
        //如果该节点位置的hash值和key的hash值相同且key值相同则直接返回该节点的第一个键值对
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
        //如果该节点是TreeNode,则调用红黑树的查找方法
            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的hash值、equals比较内容相等,如果相等则直接返回,如果该节点是TreeNode则调用红黑树的查找方法,否则则遍历该节点的链表查找。

3.4 删除remove()

源码:

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}

final Node<K,V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
    Node<K,V>[] tab; Node<K,V> p; int n, index;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (p = tab[index = (n - 1) & hash]) != null) {
        Node<K,V> node = null, e; K k; V v;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;
        else if ((e = p.next) != null) {
            if (p instanceof TreeNode)
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        //删除节点,并修复链表和红黑树
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                //链表元素重新指向
            else if (node == p)
                tab[index] = node.next;
            else
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

删除的方法和查找的方法大致相同,多了一步删除节点和修复的操作,这里就不过多介绍了

3.5 HashMap扩容机制

HashMap的长度是动态的,这正是因为HashMap的扩容机制,在HashMap中,桶数组的长度为2的n次幂,阈值大小为HashMap桶数组长度*负载因子,当HashMap的长度超过阈值时,则会进行扩容,且按照当前桶数组的长度扩容2倍,同时,阈值也会变为原来的两倍,扩容之后,要重新计算键值对的位置,并且把他们移动到合适的位置上去

注:为什么负载因子默认为0.75?

当负载因子时1时,会出现大量的hash冲突,底层的红黑树会变的复杂。会降低查询的效率。牺牲了时间来保证空间的利用率。当如果负载因子是0.5时,虽然减少了hash冲突,但是浪费了大量的空间,所以折中为0.75,当负载因子是0.75的时,空间利用率比较高,而且避免了相当多的Hash冲突,使得底层的链表或者是红黑树的高度比较低,提升了空间效率。

源码:


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;
        }
        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) {
        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 { // preserve order
                    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;
                        }
                        else {
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    if (loTail != null) {
                        loTail.next = null;
                        newTab[j] = loHead;
                    }
                    if (hiTail != null) {
                        hiTail.next = null;
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

3.5 链表树化

红黑树是一种自平衡的二叉查找树

树化源码:

static final int TREEIFY_THRESHOLD = 8;

/**
 * 当桶数组容量小于该值时,优先进行扩容,而不是树化
 */
static final int MIN_TREEIFY_CAPACITY = 64;

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
    TreeNode<K,V> parent;  // red-black tree links
    TreeNode<K,V> left;
    TreeNode<K,V> right;
    TreeNode<K,V> prev;    // needed to unlink next upon deletion
    boolean red;
    TreeNode(int hash, K key, V val, Node<K,V> next) {
        super(hash, key, val, next);
    }
}

/**
 * 将普通节点链表转换成树形节点链表
 */
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    // 桶数组容量小于 MIN_TREEIFY_CAPACITY,优先进行扩容而不是树化
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        resize();
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        // hd 为头节点(head),tl 为尾节点(tail)
        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);
    }
}

TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
    return new TreeNode<>(p.hash, p.key, p.value, next);
}

当链表长度大于等于8,桶数组容量大于等于64时,会进行链表树化,由于桶数组容量较小的时候会提高hash碰撞的概率,进而会导致链表的长度过长,所以当容量小的时候,优先对桶数组进行扩容,避免不必要的树化。

同时,桶容量较小时,扩容会比较频繁,扩容时需要拆分红黑树并重新映射。所以在桶容量比较小的情况下,将长链表转成红黑树是一件吃力不讨好的事。

参考博客:HashMap 源码详细分析(JDK1.8) - SegmentFault 思否