HashMap 结构及源码分析

HashMap 结构

HashMap的组成部分:数组 + 链表 + 红黑树。HashMap的主干是一个Node数组。NodeHashMap的基本组成单元,每一个Node包含一个key-value键值对。HashMap的时间复杂读几乎可以接近O(1)(如果出现了 哈希冲突可能会波动下),并且HashMap的空间利用率一般就是在40%左右。

HashMap 特性:

  1. HashMap 的存取是没有顺序的。
  2. K、V 均允许为 NULL。
  3. 多线程情况下该类安全,可以考虑用 HashTable。
  4. JDk8 底层是数组 + 链表 + 红黑树,JDK7 底层是数组 + 链表。
  5. 初始容量和装载因子是决定整个类性能的关键点,轻易不要动。
  6. HashMap 是 懒汉式 创建的,只有在你 put 数据时候才会 build。
  7. 单向链表转换为红黑树的时候会先变化为 双向链表 最终转换为 红黑树,双向链表跟红黑树是 共存 的,切记。
  8. 对于传入的两个 key,会强制性的判别出个高低,判别高低主要是为了决定向左还是向右。
  9. 链表转红黑树后会努力将红黑树的 root 节点和链表的头节点 跟 table[i] 节点融合成一个。
  10. 在删除的时候是先判断删除节点红黑树个数是否需要转链表,不转链表就跟 RBT 类似,找个合适的节点来填充已删除的节点。
  11. 红黑树的 root节点 不一定table[i]也就是链表的头节点是同一个哦,三者同步是靠 MoveRootToFront 实现的。而 HashIterator.remove() 会在调用 removeNode 的时候 movable=false

静态参数

 /**
     * 初始容量,默认容量=16。桶的个数不能太多或太少,如果太少,很容易触发扩容,如果太多,遍历哈希表会比较慢。
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * 数组的最大容量,一般情况下只要内存够用,哈希表不会出现问题。
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * 默认的负载因子。因此初始情况下,当存储的所有节点数 > (16 * 0.75 = 12 )时,就会触发扩容。默认负载因子(0.75)在时间和空间成本上提供了很好的折衷。较高的值会降低空间开销,但提高查找成本(体现在大多数的HashMap类的操作,包括get和put)。设置初始大小时,应该考虑预计的entry数在map及其负载系数,并且尽量减少rehash操作的次数。如果初始容量大于最大条目数除以负载因子,rehash操作将不会发生。
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * 树化的 threshold
     * 这个值表示当某个桶(数组的某个item)中,链表长度 >= 8 时,有可能会转化成树。设置为8,是系统根据泊松分布的数据分布图来设定的。
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * 在删除元素时,如果发现链表长度 <= 6,则会由树重新退化为链表。
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * 树化的 capacity
     * 链表转变成树之前,还会有一次判断,只有数组长度大于 64 才会发生转换。这是为了避免在哈希表建立初期,多个键值对恰好被放入了同一个链表中而导致不必要的转化。
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

动态参数

/**
     * HashMap 的链表数组。无论我们初始化时候是否传参,它在自扩容时总是2的次幂。
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;

    /**
     * HashMap实例中的Entry的Set集合
     * Holds cached entrySet(). Note that AbstractMap fields are used
     * for keySet() and values().
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * HashMap表中存储的实例KV个数。
     * The number of key-value mappings contained in this map.
     */
    transient int size;

    /**
     * 凡是我们做的增删改都会引发modCount值的变化,跟版本控制功能类似,可以理解成version,在特定的操作下需要对version进行检查,适用于Fai-Fast机制。
     * 在java的集合类中存在一种Fail-Fast的错误检测机制,当多个线程对同一集合的内容进行操作时,可能就会产生此类异常。比如当A通过iterator去遍历某集合的过程中,其他线程修改了此集合,此时会抛出ConcurrentModificationException异常。此类机制就是通过modCount实现的,在迭代器初始化时,会赋值expectedModCount,在迭代过程中判断modCount和expectedModCount是否一致。
     * The number of times this HashMap has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HashMap or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HashMap fail-fast.  (See ConcurrentModificationException).
     */
    transient int modCount;

    /**
     * 扩容阈值 threshold = capacity * loadFactor
     * The next size value at which to resize (capacity * load factor).
     *
     * @serial
     */
    // (The javadoc description is true upon serialization.
    // Additionally, if the table array has not been allocated, this
    // field holds the initial array capacity, or zero signifying
    // DEFAULT_INITIAL_CAPACITY.)
    int threshold;

    /**
     * 可自定义的负载因子,不过一般都是用系统自带的0.75。
     * The load factor for the hash table.
     *
     * @serial
     */
    final float loadFactor;

构造方法

  1. 默认构造方法:

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
    
  2. 传入初始化容量大小。

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    
  3. 传入初始化容量及负载因子。

    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;
        // 将初始化容量的值先赋值给 threshold 变量保存
        // 等到实例化 table 数组时,再根据 threshold 的值作为数组长度来实例化 table 数组
        this.threshold = tableSizeFor(initialCapacity);
    }
    
  4. 传入一个 map 对象。

    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }
    
    // 向 hashmap 中批量添加元素
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            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 变量保存
                    // 数组的初始化操作在下面 for 循环的 putVal 方法里
                    threshold = tableSizeFor(t);
            }
            // 如果要添加的元素个数超过了当前 hashmap 的阈值,则进行扩容
            else if (s > threshold)
                resize();
            
            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);
            }
        }
    }
    

Hash 扰动

对 hash 进行扰动,使扰动后的 hash & (table.length - 1) 结果分散,从而分布更加均匀。

扰动的关键是:hash 的低位容易出现相同,高位不容易相同,将低位进行扰动,使得每个 hash 值都尽量不一样。

static final int hash(Object key) {
    int h;
    // 将 hash 值跟将 hash 右移 16 位后的值进行异或操作
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

路由寻址

根据 hash 定位到数组中的某个桶,则应该使用 hash % table.length,取余的结果就是 hash 在桶中的位置下标。

但是由于数组 table 的长度是 2 的 n 次幂,所以取余操作等价于:hash & (table.length - 1)。使用 & 操作提高了计算的效率。

PUT

put

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

putVal

/**
     * Implements Map.put and related methods.
     *
     * @param hash         调用 hash(key) 方法得到的 hash 值
     * @param key
     * @param value
     * @param onlyIfAbsent 只有节点值为 null,才更新节点的值
     * @param evict
     * @return 更新返回节点更新前的值,插入返回 null
     */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {

    // p 表示桶中第一个元素
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    // 延迟初始化逻辑
    // hashmap 的数组为空,则初始化一个数组
    if ((tab = table) == null || (n = tab.length) == 0) {
        n = (tab = resize()).length;
    }
    // 寻址找到的元素是 null,则将元素直接放到桶里
    if ((p = tab[i = (n - 1) & hash]) == null) {
        tab[i] = newNode(hash, key, value, null);
    } else {
        Node<K,V> e; K k;
        // 前面的 if 判断,将 p 指向了寻址到的桶
        // 所以 p 表示桶中第一个节点
        // 如果 p 的 key 和 hash 与插入的 key 和 hash 相等,表示找到了与 key 相等的节点,则更新 p 的值为 value
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k)))) {
            e = p;
        } else if (p instanceof TreeNode) { // 寻址到的桶元素是红黑树节点
            // 将 p 插入到红黑树中
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        } else { // 寻址到的桶是链表结构
            // binCount:链表元素个数,从 0 开始的
            for (int binCount = 0; ; ++binCount) {
                // 如果循环到了链表尾部还没有找到与插入元素的 key 相等的节点
                if ((e = p.next) == null) {
                    // 则将新元素插到链表的末尾
                    p.next = newNode(hash, key, value, null);
                    // 当前链表元素的长度达到树化标准的话,需要进行树化
                    // 当前链表元素实际上是 binCount + 1,因为刚刚在桶最后面添加了一个节点
                    if (binCount >= TREEIFY_THRESHOLD - 1) // binCount 是从 0 开始的,-1 for 1st
                        // 将该桶中元素的存储结构从链表结构转换成红黑树结构
                        // 注意:如果 hashmap 数组的长度小于 64,则不会树化,而是会调用 resize() 方法进行扩容
                        treeifyBin(tab, hash);
                    // 遍历到尾节点,在尾节点插入一个节点,结束循环
                    break;
                }
                
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    // 遍历链表中,找到一个与插入元素的 key 相等的链表节点,结束循环
                    break;
                p = e;
            }
        }

        // e 不为 null,表示找到了与插入元素 key 一致的节点,则进行值得更新操作
        // 更新完了直接 return,不进行 ++modCount 和扩容操作
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            // 子类 LinkedHashMap 重写该方法,用来实现顺序的链表
            afterNodeAccess(e);
            return oldValue;
        }
    }
    // modCount 记录插入和删除元素次数
    ++modCount;
    // 插入新元素,size 自增
    // 如果自增后的值大于阈值,则进行扩容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

putTreeVal

/**
         * Tree version of putVal.
         */
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;
        if ((ph = p.hash) > h)
            dir = -1;
        else if (ph < h)
            dir = 1;
        else if ((pk = p.key) == k || (k != null && k.equals(pk)))
            return p;
        else if ((kc == null &&
                  (kc = comparableClassFor(k)) == null) ||
                 (dir = compareComparables(kc, k, pk)) == 0) {
            if (!searched) {
                TreeNode<K,V> q, ch;
                searched = true;
                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;
        }
    }
}

treeifyBin

/**
     * Replaces all linked nodes in bin at index for given hash unless
     * table is too small, in which case resizes instead.
     */
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    // tab == null 表示 hashmap 未初始化,调用 resize() 进行初始化
    // 准备树化时,检查到数组长度小于 64 个,不进行树化,而是数组扩容
    // 树化是因为桶中数据可能开始倾斜了,如果元素总数小于 64 个,桶中就要树化
    // 说明元素倾斜较严重,需要对数组进行扩容,尽量使元素分散的分布
    // 扩容后的总体查询效率会比单个桶中元素的树化后的查询效率要好
    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);
            // 第一次插入,p 是头结点
            if (tl == null)
                hd = p;
            else {
                // 在 tl 尾部追加节点
                p.prev = tl;
                tl.next = p;
            }
            // tl 指向每一个插入的节点
            tl = p;
        } while ((e = e.next) != null);
        
        // 桶指向将红黑树的头结点
        if ((tab[index] = hd) != null)
            // 将树转成红黑树
            hd.treeify(tab);
    }
}

treeify

/**
         * Forms tree of the nodes linked from this node.
         */
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);
}

moveRootToFront

确保将root节点挪动到table[first]上,如果红黑树构建成功而没成功执行这个任务会导致tablle[first]对应的节点不是红黑树的root节点。正常执行的时候主要步骤分2步。

  1. 找到跟节点然后将 root节点放到跟节点,至此关于红黑树到操作搞定。
  2. 原来链表头是 first节点,现在将可能是中间节点的 root节点挪到 first节点前面。
/**
         * Ensures that the given root is the first node of its bin.
         */
static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
    int n;
    if (root != null && tab != null && (n = tab.length) > 0) {
        int index = (n - 1) & root.hash;
        TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
        if (root != first) {
            Node<K,V> rn;
            tab[index] = root;
            TreeNode<K,V> rp = root.prev;
            if ((rn = root.next) != null)
                ((TreeNode<K,V>)rn).prev = rp;
            if (rp != null)
                rp.next = rn;
            if (first != null)
                first.prev = root;
            root.next = first;
            root.prev = null;
        }
        assert checkInvariants(root);
    }
}

其中 checkInvariants函数的作用:校验TreeNode对象是否满足红黑树和双链表的特性。因为并发情况下会发生很多异常。

resize

元素个数达到阈值了,需要扩容来减少 hash 碰撞,提高查询的效率。

// HashMap允许的最大容量,我理解就是数组的最大长度,而不是键值对总数
static final int MAXIMUM_CAPACITY = 1 << 30;
// 数组默认初始长度
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 默认的加载因子 
static final float DEFAULT_LOAD_FACTOR = 0.75f;

final Node<K,V>[] resize() {
    // 把当前 HashMap 的数组赋值给 oldTab
    Node<K,V>[] oldTab = table;
    // 取得老数组的长度,为 null 说明 HashMap 还没完成初始化,返回 0,否则返回数组长度
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    // 把当前 HashMap 的阈值赋值给 oldThr
    int oldThr = threshold;
    // 定义新的数组长度 newCap,新的阈值 newThr,默认为 0
    int newCap, newThr = 0;
    // 如果 oldCap 大于 0,说明老数组至少已经初始化完成了
    if (oldCap > 0) {
        // 如果老数组的长度 oldCap 大于等于MAXIMUM_CAPACITY,说明数组长度已经超过最大限制2的30次方了
        if (oldCap >= MAXIMUM_CAPACITY) {
            // 就不会再扩大数组了,直接把 Integer.MAX_VALUE(2^31-1) 赋值给阈值,这样能避免再次触发扩容
            threshold = Integer.MAX_VALUE;
            // 然后返回旧数组,这步可以理解成数组已经无法再扩容了
            return oldTab;
        }
        // 否则就把旧的数组长度 oldCap 左移一位,即新数组长度 newCap 扩容一倍
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY
                 && oldCap >= DEFAULT_INITIAL_CAPACITY)
            // 如果新数组长度 newCap 要小于 MAXIMUM_CAPACITY 并且老的数组容量大于 DEFAULT_INITIAL_CAPACITY
            // 则将新阈值设置为原来阈值的 2 倍,其它情况都是容量乘以负载因子 
            newThr = oldThr << 1; // double threshold
    }
    // 如果老数组的长度 oldCap 并没有大于 0,说明还没做初始化操作,但是这时它的旧阈值 oldThr 却大于 0,这说明了构造 HashMap 时传入了初始容量,而 HashMap 会根据传入的初始容量来定义阈值,这里给出部分代码参考:this.threshold = tableSizeFor(initialCapacity),而数组的初始化其实是在 putVal 方法里才完成的,这也就能理解为什么有阈值而数组却还没初始化了
    else if (oldThr > 0)
        // 那就把阈值值赋值给新数组长度的变量 newCap
        newCap = oldThr;
    // 走到这步,就说明旧阈值和旧数组都还没做初始化,说明调用的是 HashMap 无参的构造函数    
    else {
        // 初始化新数组长度 newCap 为 DEFAULT_INITIAL_CAPACITY(16)
        newCap = DEFAULT_INITIAL_CAPACITY;
        // 初始化新阈值 newThr 为:加载因子 * 默认容量(0.75 * 16 = 12)
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }

    // 如果新阈值等于 0
    if (newThr == 0) {
        // 新数组长度 newCap * 负载因子 loadFactor 的值赋值给 ft
        float ft = (float)newCap * loadFactor;
        // 然后判断下新数组长度 newCap 是否超过最大容量,同时 ft 的值如果超过 MAXIMUM_CAPACITY,则设置为 Integer.MAX_VALUE,否则返回 ft
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }

    // 把新阈值 newThr 赋值给 HashMap 里代表阈值的属性字段 threshold
    threshold = newThr;
    @SuppressWarnings({"rawtypes","unchecked"})
    // 创建一个长度为 newCap 的新数组,可以理解成,如果是在做初始化数组操作的话,那这就是初始化的数组,如果是在做扩容操作的话,那这就是新数组,是要用来扩容的数组
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
    // 把新数组赋值给 HashMap 里代表数组的属性字段 table
    table = newTab;

    // 如果旧数组不是 null,说明要扩容,那接下来就要迁移旧数据到新数组里了
    if (oldTab != null) {
        // 开始循环旧数组,oldCap 是旧数组长度
        // 旧 map 元素的迁移是一个桶一个桶来迁移的
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            // 取得当前下标的数组节点,赋值给变量 e,并判断是否为 null 
            if ((e = oldTab[j]) != null) {
                // 不为 null,说明旧数组在这个下标里有值,先把旧数组的这个下标位置的引用设置为 null
                oldTab[j] = null;
                // 如果 e 的后继节点为 null,说明这个桶里就一个节点
                if (e.next == null)
                    // 那就通过 [e.hash & (newCap - 1)] 计算出对应的新数组下标位置,节点设置为 e
                    newTab[e.hash & (newCap - 1)] = e;
                // 如果 e 节点是 TreeNode 类型,说明结构已经是红黑树了 
                else if (e instanceof TreeNode)
                    // 那就调用 split() 方法给红黑树做扩容
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                // 否则的话就是链表结构
                else { 
                    // (参考 treeifyBin 方法的实现)
                    // 则 loHead 是链表的 head 节点,loTail 是链表的 tail 节点
                    Node<K,V> loHead = null, loTail = null;
                    // hiHead 指向链表的 head 节点,hiTail 指向链表的 tail 节点
                    Node<K,V> hiHead = null, hiTail = null;
                    // 定义一个 Node 类型的变量 next
                    Node<K,V> next;
                    // 外层的 for 循环遍历的是数组,这里的 do ... while 循环遍历的是每个桶中的链表
                    do {
                        // next 记录 e 的后继节点
                        next = e.next;
                        // e.hash 与旧数组容量作 & 运算,如果结果为 0,则元素在新数组中的下标不变
                        if ((e.hash & oldCap) == 0) {
                            // 当前链表里还没有节点,则 e 是第一个节点
                            if (loTail == null)
                                // 则将 head 节点指向 e
                                loHead = e;
                            else // 链表里已经有节点插入了
                                // 将元素 e 追加到链表的尾节点
                                loTail.next = e;
                            // 然后将元素 e 作为尾节点
                            loTail = e;
                        }
                        // e.hash 与旧数组容量作 & 运算,如果结果不为 0(则结果为 1)
                        else { // 代码块里逻辑同上
                            if (hiTail == null)
                                hiHead = e;
                            else
                                hiTail.next = e;
                            hiTail = e;
                        }
                        // 把桶中链表元素遍历完
                    } while ((e = next) != null);

                    // 遍历完了桶中链表元素
                    // 下面开始将取出来的桶中的所有链表节点迁移到新 map 中
                    
                    // 如果 lo 链表 tail 节点不为 null(如果此链表有元素)
                    if (loTail != null) {
                        loTail.next = null;
                        // 该链表在新数组中的位置下标,跟在原数组中的位置下标一致
                        // 新数组下标 j 所在桶指向 lo 链表 head 节点
                        // j 为该链表在旧数组中的索引位置
                        newTab[j] = loHead;
                    }
                    // 逻辑同上
                    if (hiTail != null) {
                        hiTail.next = null;
                        // 该链表在新数组中的位置下标是:在原数组中的位置下标 + 原数组的长度
                        // 将新数组下标(j + oldCap)所在桶指向 hi 链表 head 节点
                        // j + oldCap 即旧数组索引 + 旧数组长度
                        newTab[j + oldCap] = hiHead;
                    }
                }
            }
        }
    }
    return newTab;
}

数组桶中链表迁移时,迁移到新数组的下标原理如下:

假如 n = 16
hash & n = hash & 10000 = n 或者 0
桶的下标 i = hash & (n - 1)

扩容时,新数组的容量 = 2n
hash & (2n - 1)
= hash & (n + (n - 1))
// 可以这样加是因为,n 只有一位是 1,后面都是 0,(n - 1)前面都是 0,后面
= hash & n + hash & (n - 1)
= (n 或者 0) + i
= (n + i) 或者 i

所以扩容后的数组元素的位置要么跟原数组索引一样,要么是原数组索引 + 原数组容量
关键在于,数组的容量 n 要是 2 的幂次方,n 的二进制中,只有一位是 1,其前后位都是 0,即 hash & n = n 或者 0

split

扩容后如何处理原来一个table[i]上的红黑树,代码的整体思路跟处理链表的时候差不多。

/**
         * Finds the node starting at root p with the given hash and key.
         * The kc argument caches comparableClassFor(key) upon first use
         * comparing keys.
         */
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;
        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;
}

tieBreakOrder

对两个对象进行比较,一定能比出个高低。

  1. a 跟 b 都是字符串则直接在if判断里比拼完毕
  2. a 跟 b 都是对象则直接查看对象在JVM中的hash地址,然后比较。
/**
         * Tie-breaking utility for ordering insertions when equal
         * hashCodes and non-comparable. We don't require a total
         * order, just a consistent insertion rule to maintain
         * equivalence across rebalancings. Tie-breaking further than
         * necessary simplifies testing a bit.
         */
        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;
        }

REMOVE

remove

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

removeNode

/**
     * Implements Map.remove and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to match if matchValue, else ignored
     * @param matchValue if true only remove if value is equal
     * @param movable if false do not move other nodes while removing
     * @return the node, or null if none
     */
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 不为空
        (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)))) {
                        // e 是要删除的节点
                        node = e;
                        break;
                    }
                    // p 表示要删除的链表中的节点 e 的上一个节点
                    // 因为执行完 p = e 后,e = e.next ,之后如果 e 是要删除的节点,就 break 跳出循环了
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        // 如果在桶中找到了要删除的节点 node
        // 如果 !matchValue 是 true,则 value 不匹配也可以删除
        // 或者 node.value 要和 value 相等,即匹配上了 value 才删除该节点
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            // node 是红黑树节点,调用 removeTreeNode 方法从红黑树中删除该节点
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            else if (node == p) // 表示删除的是桶中第一个节点(node = p)
                tab[index] = node.next;
            else // 删除的是链表中的节点
                // p 表示要删除的链表中的节点 node 的上一个节点
                // p 的后续节点指向要删除节点 node 的后续节点,没有指针指向 node 节点了,
                // 后续 node 会被回收掉
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

removeTreeNode

/**
         * Removes the given node, that must be present before this call.
         * This is messier than typical red-black deletion code because we
         * cannot swap the contents of an interior node with a leaf
         * successor that is pinned by "next" pointers that are accessible
         * independently during traversal. So instead we swap the tree
         * linkages. If the current tree appears to have too few nodes,
         * the bin is converted back to a plain bin. (The test triggers
         * somewhere between 2 and 6 nodes, depending on tree structure).
         */
final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
                          boolean movable) {
    int n;
    if (tab == null || (n = tab.length) == 0)
        return;
    int index = (n - 1) & hash;
    TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
    TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
    if (pred == null)
        tab[index] = first = succ;
    else
        pred.next = succ;
    if (succ != null)
        succ.prev = pred;
    if (first == null)
        return;
    if (root.parent != null)
        root = root.root();
    if (root == null
        || (movable
            && (root.right == null
                || (rl = root.left) == null
                || rl.left == null))) {
        tab[index] = first.untreeify(map);  // too small
        return;
    }
    TreeNode<K,V> p = this, pl = left, pr = right, replacement;
    if (pl != null && pr != null) {
        TreeNode<K,V> s = pr, sl;
        while ((sl = s.left) != null) // find successor
            s = sl;
        boolean c = s.red; s.red = p.red; p.red = c; // swap colors
        TreeNode<K,V> sr = s.right;
        TreeNode<K,V> pp = p.parent;
        if (s == pr) { // p was s's direct parent
            p.parent = s;
            s.right = p;
        }
        else {
            TreeNode<K,V> sp = s.parent;
            if ((p.parent = sp) != null) {
                if (s == sp.left)
                    sp.left = p;
                else
                    sp.right = p;
            }
            if ((s.right = pr) != null)
                pr.parent = s;
        }
        p.left = null;
        if ((p.right = sr) != null)
            sr.parent = p;
        if ((s.left = pl) != null)
            pl.parent = s;
        if ((s.parent = pp) == null)
            root = s;
        else if (p == pp.left)
            pp.left = s;
        else
            pp.right = s;
        if (sr != null)
            replacement = sr;
        else
            replacement = p;
    }
    else if (pl != null)
        replacement = pl;
    else if (pr != null)
        replacement = pr;
    else
        replacement = p;
    if (replacement != p) {
        TreeNode<K,V> pp = replacement.parent = p.parent;
        if (pp == null)
            root = replacement;
        else if (p == pp.left)
            pp.left = replacement;
        else
            pp.right = replacement;
        p.left = p.right = p.parent = null;
    }

    TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);

    if (replacement == p) {  // detach
        TreeNode<K,V> pp = p.parent;
        p.parent = null;
        if (pp != null) {
            if (p == pp.left)
                pp.left = null;
            else if (p == pp.right)
                pp.right = null;
        }
    }
    if (movable)
        moveRootToFront(tab, r);
}

untreeify

红黑树退化成链表。

/**
         * Returns a list of non-TreeNodes replacing those linked from
         * this node.
         */
final Node<K,V> untreeify(HashMap<K,V> map) {
    Node<K,V> hd = null, tl = null;
    for (Node<K,V> q = this; q != null; q = q.next) {
        Node<K,V> p = map.replacementNode(q, null);
        if (tl == null)
            hd = p;
        else
            tl.next = p;
        tl = p;
    }
    return hd;
}

balanceDeletion

关于这个问题可以直接参考红黑树添加跟删除RBT。

GET

get

public V get(Object key) {
    Node<K,V> e;
    // 找到了返回元素值,否则返回 null
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

getNode

final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    // 根据 key 的 hash 定位到数组元素
    // 如果数组不为空,并且定位到的数组元素也不为空
    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);
        }
    }
    // 数组为空、定位到的数组桶元素为空、桶中元素也没有匹配到,则直接返回 null
    return null;
}

getTreeNode

// 获取树节点
final TreeNode<K,V> getTreeNode(int h, Object k) {
    return ((parent != null) ? root() : this).find(h, k, null);
}

root


find

/**
         * Finds the node starting at root p with the given hash and key.
         * The kc argument caches comparableClassFor(key) upon first use
         * comparing keys.
         */
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;
        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;
}

ComparableClassFor

查询该key是否实现了Comparable接口。

/**
     * Returns x's Class if it is of the form "class C implements
     * Comparable<C>", else null.
     */
static Class<?> comparableClassFor(Object x) {
    if (x instanceof Comparable) {
        Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
        if ((c = x.getClass()) == String.class) // bypass checks
            return c;
        if ((ts = c.getGenericInterfaces()) != null) {
            for (int i = 0; i < ts.length; ++i) {
                if (((t = ts[i]) instanceof ParameterizedType) &&
                    ((p = (ParameterizedType)t).getRawType() ==
                     Comparable.class) &&
                    (as = p.getActualTypeArguments()) != null &&
                    as.length == 1 && as[0] == c) // type arg is c
                    return c;
            }
        }
    }
    return null;
}

compareComparables

既然实现了 Comparable 接口就用该实现进行对比判断如何何去何从。

/**
     * Returns k.compareTo(x) if x matches kc (k's screened comparable
     * class), else 0.
     */
@SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
static int compareComparables(Class<?> kc, Object k, Object x) {
    return (x == null || x.getClass() != kc ? 0 :
            ((Comparable)k).compareTo(x));
}
原文地址:https://www.cnblogs.com/wu726/p/15708894.html