HashMap源码解析

HashMap

元素顺序:HashMap中元素是乱序的,并不会按照某种规律排序。在添加元素时新元素被插入到最后,扩容时,最后一个元素又被放置在桶的第一个元素。

默认容量为16,负载因子为0.75,扩容时,容量会x2扩大,扩容阈值也x2。

元素以一个数组为桶作为存储,数组的每一个索引位便是一个桶,桶中元素形成链表,当链表长度达到8,并且数组长度(不是总元素个数)达到64,桶中链表会树化为红黑树,以减少哈希碰撞。但是如果在扩容时发现有hash桶由于移除元素或者扩容迁移,导致桶中元素小于6,那么会反树化为链表。

内部类

链表节点Node

/**
 * 链表节点
 */
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;
        }
}

红黑树节点TreeNode

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

关键属性

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默认容量16
static final int MAXIMUM_CAPACITY = 1 << 30; // 最大容量
static final float DEFAULT_LOAD_FACTOR = 0.75f; // 默认负载因子,在泊松分布下哈希碰撞较少

int threshold; // 扩容阈值,当size达到这个值,将会触发扩容
final float loadFactor; // 负载因子


// 当某个桶的链表长度达到8,并且table数组长度(注意是table的长度,而不是总的元素个数)达到64才会树化,否则通过扩容即可减少哈希冲突
static final int TREEIFY_THRESHOLD = 8;
static final int MIN_TREEIFY_CAPACITY = 64;
// 当某个桶中的元素个数减少到6个时,将由红黑树退化回链表(反树化)
static final int UNTREEIFY_THRESHOLD = 6;

transient Node<K,V>[] table; // 存储元素,第一次使用时才会初始化,大小始终是2的次幂
transient int size; // 实际元素个数 size<capacity
transient int modCount; // 记录HashMap的结构性修改次数 add remove resize...

构造函数

在创建HashMap时并没有计算hashMap容量和初始化存储数组table。存储数组table将会在第一次添加元素时进行初始化。

/**
* 指定初始容量和负责因子
*/
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);
}

/**
 * 指定初始容量,使用默认负载因此 0.75
 */
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
 * 默认初始容量(16) 默认负载因子(0.75)
 */
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);
}
/**
 * 根据容量计算扩容阈值
 */
static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
/**
 * 计算key的hash值。将高16位和低16位做与运算,将高位的影响降到低位,有利于减少哈希碰撞
 */
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

添加元素

/** 
 * 新增元素
 */
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}


/**
 * 新增元素。
 * 如果key-value已存在返回oldVal,否则返回null。返回null并不代表key不存在,也可能由于value为null
 */
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;
     // 如果桶中还没有元素,则当前新增元素作为桶的第一个元素
     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;
         // 不是同一个key,并且桶中元素已经树化
         else if (p instanceof TreeNode)
             e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
         // 不是同一个key,并且桶中元素是链表
         else {
             for (int binCount = 0; ; ++binCount) {
                 // 已经找完了所有hash相等的元素,仍没有匹配,所以创建一个新节点加入
                 if ((e = p.next) == null) {
                     // 将新增元素插入链表最后
                     p.next = newNode(hash, key, value, null);
                     // 如果放入元素后,链表长度到了8,尝试进行树化
                     if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                         treeifyBin(tab, hash);
                     break;
                 }
                 // 判断是否有相等的key
                 if (e.hash == hash &&
                     ((k = e.key) == key || (key != null && key.equals(k))))
                     // 有相同的key
                     break;
                 p = e;
             }
         }
         // e 不等于null,说明存在相同的key
         if (e != null) { // existing mapping for key
             V oldValue = e.value;
             // 如果onlyIfAbsent=false 或者key对应的oldVal为null,那么设置已存在的key的val为新值
             if (!onlyIfAbsent || oldValue == null)
                 e.value = value;
             // LinkedHashMap中使用
             afterNodeAccess(e);
             // 如果存在key-val,则返回旧的val
             return oldValue;
         }
     }
     // 没有存在的key,那么走到这里
    // 因为已经新增了一个元素,所以HashMap修改次数+1
     ++modCount;
     // 新增元素后,如果数组长度达到了扩容阈值,进行扩容
     if (++size > threshold)
         resize();
     // LinkedHashMap使用
     afterNodeInsertion(evict);
     return null;
 }

扩容

/**
 * 当HashMap元素个数到达threshold时,将会触发扩容。
 * 扩容时会将原桶中的链表(树)划分为两个链表(两棵树)
 *
 * Note:第一次添加元素时也会调用该方法进行数组table的初始化
 *
 * 每次扩容容量capacity扩大一倍,扩容阈值threshold扩大一倍
 */
final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    // 旧数组的大小
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    // 旧数组大小大于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
    }
    // 旧扩容阈值大于0(第一次添加元素时进入到这里,初始化容量为扩容阈值)
    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;
    // 根据新的capacity创建数组替换掉老的数组
    @SuppressWarnings({"rawtypes","unchecked"})
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;// 如果是第一次添加元素,那么走到这里初始化完整,程序返回
    
    // 是扩容调用到该方法
    if (oldTab != null) {
        // 遍历hash桶
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            // 从每一个hash桶的第一个元素开始遍历
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                // e是桶中的最后一个元素
                if (e.next == null)
                    // 确定e在桶中的位置,并设置e
                    newTab[e.hash & (newCap - 1)] = e;
                // 桶中元素是红黑树
                else if (e instanceof TreeNode)
                    // 在扩容中,如果发现桶中元素已经不满足树化条件,将进行反树化,将红黑树重新转化为链表
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                // 桶中元素是链表
                else { // preserve order
                   
                   // 如果桶中至少有2个元素,并且是以链表形式存在(桶中元素 2<= cnt < 8)会走到这里
                   // 如果e.hash & oldCap = 0 则元素视为低位元素,仍然在原桶中
                   // 如果e.hash & oldCap != 0 则元素视为高位元素,从当前索引位向前迁移oldCap个offset
                    // 如oldCap = 4, 内有三个元素hash =  3(index = 3),6(index = 2),9(index = 1)
                    // 3 & 4 = 0, 6 & 4 = 4, 9 & 4 = 0
                    // 则扩容后3,9仍然在原索引位,6将转移到6号索引位
                    // 低位的头节点、尾节点
                    Node<K,V> loHead = null, loTail = null;
                    // 高位的头节点、尾节点
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        // e.hash & oldCap = 0 视为低位节点
                        if ((e.hash & oldCap) == 0) {
                            // 桶中的第一个元素作为头节点
                            if (loTail == null)
                                loHead = e;
                            else
                                loTail.next = e;
                            loTail = e;
                        }
                        // e.hash & oldCap != 0 视为高位节点
                        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;
                        // 高位元素向前迁移oldCap的offset
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

/**
 * 红黑树扩容
 *
 * @param map HashMap
 * @param tab 哈希表
 * @param index 当前所在桶
 * @param bit
 */
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
    TreeNode<K,V> b = this;
    // Relink into lo and hi lists, preserving order
    TreeNode<K,V> loHead = null, loTail = null;
    TreeNode<K,V> hiHead = null, hiTail = null;
    int lc = 0, hc = 0;
    for (TreeNode<K,V> e = b, next; e != null; e = next) {
        next = (TreeNode<K,V>)e.next;
        e.next = null;
        
        
        // 将树划分为低位、高位两棵树
        // 低位树保持在原index位置,高位树迁移到原index + oldCap位置
        if ((e.hash & bit) == 0) {
            if ((e.prev = loTail) == null)
                loHead = e;
            else
                loTail.next = e;
            loTail = e;
            ++lc;
        }
        else {
            if ((e.prev = hiTail) == null)
                hiHead = e;
            else
                hiTail.next = e;
            hiTail = e;
            ++hc;
        }
    }

    if (loHead != null) {
        // 如果低位树元素个数小于6,将反树化为链表
        if (lc <= UNTREEIFY_THRESHOLD)
            tab[index] = loHead.untreeify(map);
        else {
            tab[index] = loHead;
            if (hiHead != null) // (else is already treeified)
                loHead.treeify(tab);
        }
    }
    if (hiHead != null) {
        // 如果高位树元素个数小于6,将反树化为链表
        if (hc <= UNTREEIFY_THRESHOLD)
            tab[index + bit] = hiHead.untreeify(map);
        else {
            tab[index + bit] = hiHead;
            if (loHead != null)
                hiHead.treeify(tab);
        }
    }
}

树化

需要当前桶中节点数量达到8,并且table的长度达到64才进行树化,否则通过扩容便可以减少哈希碰撞。

树化时,先将桶中的所有元素转化为双向链表,然后在转化为树,进行平衡

/**
 * 当桶中元素数量(链表长度)到达8,并且哈希表table长度达到64,那么桶中元素数据结构将由链表转化为红黑树,以减少
 * 哈希碰撞,提高HashMap检索效率
 * 
 * 如果桶中链表长度已经达到8个,但是哈希表table长度还未达到64,那么进行扩容,而不是树化。因为扩容之后,
 * 同一个桶的元素可能被分到两个桶中,从而减少哈希碰撞
 *
 * Note:注意是哈希表table的长度达到64,不是HashMap中元素个数
 */
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    // 哈希表长度还未达到64,进行扩容,而不是树化
    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;
        // 将链表节点Node 转化为 红黑树节点TreeNode,并以双向链表的形式存在
        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);
    }
}
// 真正执行树化,从双向链表的头节点开始树化
final void treeify(Node<K,V>[] tab) {
    TreeNode<K,V> root = null;
    for (TreeNode<K,V> x = this, next; x != null; x = next) {
        next = (TreeNode<K,V>)x.next;
        x.left = x.right = null;
        // 第一个元素作为根节点且是黑节点,其他元素先依次插入到树中,再进行平衡
        if (root == null) {
            x.parent = null;
            x.red = false;
            root = x;
        }
        else {
            K k = x.key;
            int h = x.hash;
            Class<?> kc = null;
            // 从根节点开始遍历形成树
            for (TreeNode<K,V> p = root;;) {
                int dir, ph;
                K pk = p.key;
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0)
                    dir = tieBreakOrder(k, pk);

                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    x.parent = xp;
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    // 二叉树平衡
                    root = balanceInsertion(root, x);
                    break;
                }
            }
        }
    }
    // 将根节点移动到头部,因为通过平衡之后,原来的第一个元素不一定是根节点了
    moveRootToFront(tab, root);
}

获取元素

/**
 * 如果key-value存在,则返回value,否则,返回null
 */
public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}
 
/**
 * @param hash  hash(key)
 */
final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    // 1、哈希表table不空才需要查找,否则直接返回null即可
    // 2、hash & (n - 1) 位置的桶中存在元素,才进行查找,否则,直接返回null 
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        // 如果桶的第一个元素的key与查找的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) {
            // 如果第一个元素是红黑树节点,则使用树型查找
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            // 第一个元素是聊表,那么遍历链表查找,找到返回对应value,否则返回null
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

/**
 * 红黑树查找,从根节点开始搜索
 */
final TreeNode<K,V> getTreeNode(int h, Object k) {
    return ((parent != null) ? root() : this).find(h, k, null);
}

/**
 * 遍历左右子树进行查找
 */
 final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
     TreeNode<K,V> p = this;
     do {
         int ph, dir; K pk;
         // 获取左右子节点
         TreeNode<K,V> pl = p.left, pr = p.right, q;
         // 左节点
         if ((ph = p.hash) > h)
             p = pl;
         // 右节点
         else if (ph < h)
             p = pr;
         // 相同的key,返回当前节点
         else if ((pk = p.key) == k || (k != null && k.equals(pk)))
             return p;
         // 左子树为空,转移到右子树
         else if (pl == null)
             p = pr;
         // 右子树为空,转移到左子树
         else if (pr == null)
             p = pl;
         else if ((kc != null ||
                   (kc = comparableClassFor(k)) != null) &&
                  (dir = compareComparables(kc, k, pk)) != 0)
             p = (dir < 0) ? pl : pr;
         else if ((q = pr.find(h, k, kc)) != null)
             return q;
         else
             p = pl;
     } while (p != null);
     return null;
 }

移除节点

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

 /**
  * 如果存在key才需要进行移除,如果matchValue为true,那么,还需要value匹配
  * 
  * @return 存在key且移除成功返回oldVal。否则,返回null
  */
 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;
     // 1、如果当前哈希表table不为空,才需要进行移除
     // 2、当前 hash & (n - 1)位置桶不空,才需要进行移除
     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;
         // 桶的第一个元素便是要移除的key
         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 {
                 // 遍历查找相同key的元素
                 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;
             // HashMap中元素个数-1
             --size;
             afterNodeRemoval(node);
             return node;
         }
     }
     return null;
 }

原文地址:https://www.cnblogs.com/QullLee/p/12236235.html