Java集合系列07之HashMap源码分析

[toc]

前言

HashMap是一个基于哈希实现的无序散列表,存储内容是键值对(key-value),非线程安全。其定义如下:

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable

可以看到HashMap继承AbstractMap,实现了Map、Cloneable、java.io.Serializable接口。

本文源码分析基于jdk 1.8.0_121

继承关系

HashMap继承关系

java.lang.Object
   |___  java.util.AbstractMap<K,V>
       |___  java.util.HashMap<K,V>
所有已实现的接口:
Serializable, Cloneable, Map<K,V>

关系图

《Java集合系列07之HashMap源码分析》 HashMap关系图

  • tableNode型的数组,而Node其实是个单向链表,所以HashMap的底层实现是由数组和链表实现的
  • sizeHashMap的实际大小
  • threshold为是否需要调整HashMap的容量的阈值,等于加载因子乘以容量,当size达到threshold时,便对HashMap扩容至原来的两倍
  • loadFactor是加载因子
  • modCount是修改HashMap结构的计数值,用来实现fail-fast机制

需要注意的是在JDK 1.8以前HashMap的实现是数组+链表,但是哈希函数很难将元素百分百均匀分布,因此可能出现有大量的元素都存放到同一个桶中,那么便会出现一条长链表, HashMap 就相当于一个单链表结构,遍历的时间复杂度变成 O(n)JDK 1.8时引入红黑树结构来优化此种现象,时间复杂度为O(logn)。当单个链表长度大于8时,就会将链表结构转为红黑树结构,示意图如下:

《Java集合系列07之HashMap源码分析》 HashMap红黑树

图片来源【文斯莫克香吉士】博客,博客地址见参考信息【Java集合:HashMap详解(JDK 1.8)】

数据结构

链表节点数据结构定义如下:

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    // 下一个节点
    Node<K,V> next; 
    
    ...
    
}

红黑树的节点数据结构定义如下:

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

// LinkedHashMap.Entry数据结构
static class Entry<K,V> extends HashMap.Node<K,V> {
    Entry<K,V> before, after;
    
    ...
    
}

可以看到TreeNode继承于LinkedHashMap.Entry,而 LinkedHashMap.Entry 继承自 HashMap.Node

构造函数

// 默认构造函数
HashMap()

// 指定“容量大小”的构造函数
HashMap(int initialCapacity)

// 指定“容量大小”和“加载因子”的构造函数
HashMap(int initialCapacity, float loadFactor)

// 包含“子Map”的构造函数
HashMap(Map<? extends K, ? extends V> m)

从上述构造函数中我们可以看到影响HashMap的容量主要有初始容量大小initialCapacity和加载因子loadFactor,初始容量是指哈希表中桶的数量,当哈希表中的条目数与当前容量的比值超出了加载因子时,则要对该哈希表进行 rehash/resize 操作(即重建内部数据结构),将哈希表容量增加一倍。默认的加载因子是0.75,这是结合空间成本和时间成本给出的一个经验值,加载因子过大,增加时间成本;加载因子过小,则增加空间成本。因此,选取合适的加载因子很重要,可以减少rehash的次数。

API

void                 clear()
Object               clone()
boolean              containsKey(Object key)
boolean              containsValue(Object value)
Set<Entry<K, V>>     entrySet()
V                    get(Object key)
boolean              isEmpty()
Set<K>               keySet()
V                    put(K key, V value)
void                 putAll(Map<? extends K, ? extends V> map)
V                    remove(Object key)
int                  size()
Collection<V>        values()

源码分析

成员变量

// 默认的初始容量是16,必须是2的幂。
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
  
// 最大容量,必须小于2的30次方,初始容量过大将被这个值代替
static final int MAXIMUM_CAPACITY = 1 << 30;
 
// 默认加载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
 
// 存储数据的Node数组,长度必须是2的幂
// HashMap是采用拉链法实现的,每一个Node本质上是一个单向链表
transient Node<K,V>[] table;

// 红黑树代替链表的阈值
// 当一个桶中链表长度大于此数值时,应该用红黑树代替链表,以优化查找效率
static final int TREEIFY_THRESHOLD = 8;

// 红黑树还原为链表的阈值
// 扩容时,当一个桶中链表长度小于此数值时,就会把红黑树还原为链表结构
static final int UNTREEIFY_THRESHOLD = 6;

// 哈希表最小的树形化容量
// 当哈希表中的容量大于这个值时,表中的桶才能进行树形化
// 否则桶内元素太多时会扩容,而不是树形化
// 为了避免进行扩容、树形化选择的冲突,这个值不能小于 4 * TREEIFY_THRESHOLD
static final int MIN_TREEIFY_CAPACITY = 64;

// 键值对
transient Set<Map.Entry<K,V>> entrySet;

// HashMap的大小,它是HashMap保存的键值对的数量
transient int size;
 
// 阈值用于判断是否需要调整HashMap的容量(threshold 容量*加载因子)
int threshold;
  
// 加载因子实际大小
final float loadFactor;
  
// HashMap被改变的次数
transient volatile int modCount;

构造函数

// 指定“初始容量”和“加载因子”的构造函数
public HashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " +
                                           initialCapacity);
    // HashMap的最大容量是MAXIMUM_CAPACITY                                  
    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);
}

// 找到大于给定容量的最小2的幂值
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;
}

// 指定初始容量的构造函数
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

// 默认构造函数
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

// 包含子Map的构造函数
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

定位桶位置

// hash操作
static final int hash(Object key) {
    int h;
    // key.hashCode()算法原理见参考信息
    // >>> : 无符号右移
    // hashCode的高16位参与运算
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

对于给定的key,只要其hashCode()的返回值一样,那么其hash值就一样,如果用hash值对table长度取模,那么便可以让哈希表的元素分布相对均匀点。

此处源码对取模运算进行了优化,table的长度总是2的n次幂,而x mod 2^n = x & (2^n - 1),因此源码使用i = (n - 1) & hash来对table长度取模,从而找到对应的索引位置,&比%具有更高的效率。

增加元素

// 把key-value添加到HashMap中
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

// 把给定的hash,key,value添加到HashMap中
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为null或长度为0,则resize
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // (n-1) & hash寻找索引值
    // 如果在table中该索引值对应节点为空,则新建一个节点
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        // 节点p满足hash值和key值跟传入的hash值和key值相等则让e=p
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        // 如果p属于红黑树型,则调用putTreeVal查找目标节点
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            // 遍历此链表, binCount用于统计节点数
            for (int binCount = 0; ; ++binCount) {
                // p.next为null,则新建一个节点插入链表尾部
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    // binCount大于8,则替换为红黑树结构
                    // 减1是因为循环是从p节点的下一个节点开始的
                    if (binCount >= TREEIFY_THRESHOLD - 1) 
                        treeifyBin(tab, hash);
                    break;
                }
                // 找到对应节点,则终止循环
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        // 已存在给定的key的映射关系
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            // 满足条件,替换value值
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);  // Callbacks to allow LinkedHashMap post-actions
            return oldValue;
        }
    }
    // 改变modCount
    ++modCount;
    // 插入节点后超出容量阈值,则扩容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);  // Callbacks to allow LinkedHashMap post-actions
    return null;
}

// 添加m中所有元素到HashMap中
public void putAll(Map<? extends K, ? extends V> m) {
    putMapEntries(m, true);
}

// 将m中元素加入到HashMap中
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
    int s = m.size();
    if (s > 0) {
        // 如果table为null,则设置threshold值
        if (table == null) { // pre-size
            float ft = ((float)s / loadFactor) + 1.0F;
            int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                     (int)ft : MAXIMUM_CAPACITY);
            if (t > threshold)
                threshold = tableSizeFor(t);
        }
        // 如果table不为null,s大于threshold,则resize
        else if (s > threshold)
            resize();
        // 把m中元素逐一加入HashMap中
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
            K key = e.getKey();
            V value = e.getValue();
            putVal(hash(key), key, value, false, evict);
        }
    }
}

红黑树增加元素

final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                               int h, K k, V v) {
    Class<?> kc = null;
    boolean searched = false;
    // 查找根节点,索引处头节点不一定为红黑树头节点
    TreeNode<K,V> root = (parent != null) ? root() : this;
    // 添加元素时,从根节点遍历,
    for (TreeNode<K,V> p = root;;) {
        int dir, ph; K pk;
        // 传入的hash值小于p节点的hash值
        // 则令dir=-1,表示向p的左边查找树
        if ((ph = p.hash) > h)
            dir = -1;
        // 传入的hash值大于p节点的hash值
        // 则令dir=1,表示向p的右边查找树
        else if (ph < h)
            dir = 1;
        // 如果当前节点的哈希值、键和要添加的都一致,就返回当前节点
        else if ((pk = p.key) == k || (k != null && k.equals(pk)))
            return p;
        // k所属的类没有实现Comparable接口或者k和p节点的key值相等
        else if ((kc == null &&
                  (kc = comparableClassFor(k)) == null) ||
                 (dir = compareComparables(kc, k, pk)) == 0) {
            // 第一次符合条件,方法只执行一次 
            if (!searched) {
                TreeNode<K,V> q, ch;
                searched = true;
                // 如果从当前节点p所在子树中可以找到要添加的节点,则直接返回
                if (((ch = p.left) != null &&
                     (q = ch.find(h, k, kc)) != null) ||
                    ((ch = p.right) != null &&
                     (q = ch.find(h, k, kc)) != null))
                    return q;
            }
            // 哈希值相等,但键无法比较
            // 通过自定义规则来插入节点
            dir = tieBreakOrder(k, pk);
        }

        TreeNode<K,V> xp = p;
        // 要插入的节点比当前节点小就插到左子树,大就插到右子树
        if ((p = (dir <= 0) ? p.left : p.right) == null) {
            Node<K,V> xpn = xp.next;
            TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
            if (dir <= 0)
                xp.left = x;
            else
                xp.right = x;
            xp.next = x;
            x.parent = x.prev = xp;
            if (xpn != null)
                ((TreeNode<K,V>)xpn).prev = x;
            // 必要的平衡操作
            moveRootToFront(tab, balanceInsertion(root, x));
            return null;
        }
    }
}

// 此方法用于a和b哈希值相等,但无法比较时
// 自定义一个规则保持平衡
static int tieBreakOrder(Object a, Object b) {
    int d;
    if (a == null || b == null ||
        (d = a.getClass().getName().
         compareTo(b.getClass().getName())) == 0)
        d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
             -1 : 1);
    return d;
}

获取元素

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

// 根据给定的hash和key找到对应节点
final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    // table不为null且table的length大于0且hash对应的桶不为空
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        // 如果first.hash和给定hash相同且key也相同,则返回first.key
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        // first.next不为null
        if ((e = first.next) != null) {
            // first是红黑树节点,则调用getTreeNode
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            // 循环直至next为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);
}

// 根据hash值和key查找节点
// 因为红黑树有序,所以相当于折半查找
// 红黑树具有平衡二叉树的特点:左节点<根节点<右节点
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;
        // 给定的hash值小于p节点的hash值, 则向左遍历
        if ((ph = p.hash) > h)
            p = pl;
        // 给定的hash值大于p节点的hash值, 则向右遍历
        else if (ph < h)
            p = pr;
        // p节点为目标节点,则返回之
        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;
        // k所属的类实现Comparable接口或者k和p节点的key值不等
        else if ((kc != null ||
                  (kc = comparableClassFor(k)) != null) &&
                 (dir = compareComparables(kc, k, pk)) != 0)
            // k<pk 则向左遍历,否则向右遍历
            p = (dir < 0) ? pl : pr;
        // k所属的类没有实现Comparable接口,则直接向右遍历
        else if ((q = pr.find(h, k, kc)) != null)
            return q;
        // 上一步向右遍历为空,则再向左遍历
        else
            p = pl;
    } while (p != null);
    return null;
}

删除元素

// 删除键为key的元素
public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}

// 删除键为key的元素
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;
    // table不为null且table的length大于0且hash对应的桶不为空
    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;
        // p为目标节点,则让node=p
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;
        // 循环遍历直至找到满足的节点 
        else if ((e = p.next) != null) {
            // 如果p属于TreeNode型,则调用getTreeNode方法
            if (p instanceof TreeNode)
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                do {
                    // 当节点的hash值和key与传入的相同,则该节点即为目标节点
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        // 如果node不为null,即找到了目标节点
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            // node属于TreeNode型,则调用removeTreeNode方法
            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值
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

resize

// 重新调整HashMap大小
final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    // 旧HashMap不为null且length大于0
    if (oldCap > 0) {
        // 旧HashMap的容量超过最大容量值
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        // 扩容至原来两倍
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
            newThr = oldThr << 1;
    }
    // 旧表的容量为0,旧表的阈值不为0
    else if (oldThr > 0) 
        // 新表的容量设置为老表的阈值
        newCap = oldThr;
    // 旧表阈值为0,设置新表容量为默认容量,阈值为默认阈值
    else {               
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    // 如果新表的阈值为0, 则通过新的容量*负载因子获得阈值
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    // 重设threshold
    threshold = newThr;
    // 新建一个table数组
    @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    table = newTab;
    // 将旧table中所有元素添加到新table中
    if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            // 索引值为j的老表头节点赋值给e
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                // e.next为null,则该位置只有1个节点
                // 计算该节点在新表下的索引位置,并放在该处
                if (e.next == null)
                    newTab[e.hash & (newCap - 1)] = e;
                // 如果是红黑树结构,且元素数量小于还原阈值UNTREEIFY_THRESHOLD 
                // 则树形结构还原为链表结构
                else if (e instanceof TreeNode)
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                else { // preserve order
                    // 存储跟原索引位置相同的节点
                    Node<K,V> loHead = null, loTail = null;
                    // 存储索引位置为:原索引+oldCap的节点
                    Node<K,V> hiHead = null, hiTail = null;
                    Node<K,V> next;
                    do {
                        next = e.next;
                        // e的hash值与旧表的容量进行与运算为0,则扩容后的索引位置跟老表的索引位置一样
                        if ((e.hash & oldCap) == 0) {
                            // loTail为空, 代表该节点为第一个节点
                            if (loTail == null)
                                // 将第一个节点赋值给lohead
                                loHead = e;
                            else
                                // 否则将该节点加在loTail后面
                                loTail.next = e;
                            // loTail赋值为节点e
                            loTail = e;
                        }
                        // e的hash值与老表的容量进行与运算为1,则扩容后的索引位置为:老表的索引位置+oldCap
                        else {
                            // hiTail为空, 代表该节点为第一个节点
                            if (hiTail == null)
                                // 将第一个节点赋值给hihead
                                hiHead = e;
                            else
                                // 否则将该节点加在hiTail后面
                                hiTail.next = e;
                            // hiTail赋值为节点e
                            hiTail = e;
                        }
                    } while ((e = next) != null);
                    if (loTail != null) {
                        // 最后一个节点的next设为空
                        loTail.next = null;
                        // 新表原索引j处设为lohead
                        newTab[j] = loHead;
                    }
                    if (hiTail != null) {
                        // 最后一个节点的next设为空
                        hiTail.next = null;
                        // 新表原索引j+oldCap处设为hiHead
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

是否包含元素

// 是否包含key
public boolean containsKey(Object key) {
    return getNode(hash(key), key) != null;
}

// 是否包含value
public boolean containsValue(Object value) {
    Node<K,V>[] tab; V v;
    // 双重循环查找value
    if ((tab = table) != null && size > 0) {
        for (int i = 0; i < tab.length; ++i) {
            for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                if ((v = e.value) == value ||
                    (value != null && value.equals(v)))
                    return true;
            }
        }
    }
    return false;
}

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;
    }
    
    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }

    public final boolean equals(Object o) {
        if (o == this)
            return true;
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            if (Objects.equals(key, e.getKey()) &&
                Objects.equals(value, e.getValue()))
                return true;
        }
        return false;
    }
}

树形化操作

// 将桶类链表结构转化为树形结构
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    // 哈希表为空或哈希表长度小于树形化容量阈值(默认64),则执行resize操作
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        resize();
    // 哈希表中的元素个数超过了树形化容量阈值,进行树形化
    // e 是给定hash值对应的桶的第一个链表节点
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        TreeNode<K,V> hd = null, tl = null;
        do {
            // 新建一个TreeNode节点
            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节点
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
    return new TreeNode<>(p.hash, p.key, p.value, next);
}

// 形成红黑树
final void treeify(Node<K,V>[] tab) {
    TreeNode<K,V> root = null;
    // this为调用此方法的TreeNode
    for (TreeNode<K,V> x = this, next; x != null; x = next) {
        next = (TreeNode<K,V>)x.next;
        x.left = x.right = null;
        // 还没有根节点将x设为根节点
        // 设置root为黑色
        if (root == null) {
            // 根节点没有父节点
            x.parent = null;
            x.red = false;
            root = x;
        }
        else {
            K k = x.key;
            int h = x.hash;
            Class<?> kc = null;
            // 从根节点开始,遍历所有节点跟当前节点x比较,调整位置
            for (TreeNode<K,V> p = root;;) {
                int dir, ph;
                K pk = p.key;
                // 待比较节点的哈希值比x大时, dir为-1,向左查找
                // 否则dir为1,向右查找
                if ((ph = p.hash) > h) 
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                // x的hash值和p的hash值相等,则比较key值
                // k没有实现Comparable接口或者x节点的key和p节点的key相等
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0)
                    // 通过自定义规则来判断向左还是向右查找
                    dir = tieBreakOrder(k, pk);
                
                // 待比较节点的哈希值比x大,x就是左孩子,否则x是右孩子 
                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;
                }
            }
        }
    }
    // 将root节点调整为table索引处头节点
    moveRootToFront(tab, root);
}

遍历

假设keyvalue都是String

  • 根据entrySet()通过Iterator遍历
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()){
    Map.Entry entry = (Map.Entry)iter.next();
    key = (String)entry.getKey();
    value = (String)entry.getValue();
}
  • 根据keySet()通过Iterator遍历
Iterator iter = map.keySet().iterator();
while(iter.hasNext()){
    key = (String)iter.next();
    value = (String)map.get(key);
}
  • 根据value()通过Iterator遍历
Iterator iter = map.values().iterator();
while(iter.hasNext()){
    value = (String)iter.next;
}

参考信息

    原文作者:weixin_34327761
    原文地址: https://blog.csdn.net/weixin_34327761/article/details/91019755
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞