Java集合之 Map源码解析

HashMap:
也是我们平时开发中使用频率很高的双列集合,直接父类是AbstractMap,是基于hash表存储的一种集合。
几个重要的类变量:

    //hash表的初始化大小,默认为16.是基于数组实现的。
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

   //hash表最大容量,最大值不能超过这个数值。
    static final int MAXIMUM_CAPACITY = 1 << 30;

   //默认加载因子,当我们初始化时默认hash表为16,当键值对的大小大于16*0.75=12时,就会触发扩容
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

   //树形化得阈(yu)值,当hash表中某一个桶位置存储链表的长度大于8时,将链表转换为红黑树,至于为什么是8,因为理想状态下哈希表的每个箱子中,元素的数量遵守泊松分布,当链表长度大于8的时候,得出的概率几乎为0.
    static final int TREEIFY_THRESHOLD = 8;

  //当红黑树的大小小于6,解散红黑树
    static final int UNTREEIFY_THRESHOLD = 6;

    //在转变成树之前,还会有一次判断,只有键值对数量大于 64 才会发生转换。这是为了避免在哈希表建立初期,多个键值对恰好被放入了同一个链表中而导致不必要的转化。
    static final int MIN_TREEIFY_CAPACITY = 64;

    //map容量
    transient Node<K,V>[] table;

   //存储键值对个数
    transient int size;

   //修改计数
    transient int modCount;

  //扩容阈值
    int threshold;

    //加载因子
    final float loadFactor;
//Map存储的基本单元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; }
       //计算当前元素的hash
        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;
        }
    }
//添加元素
 public V put(K key, V value) {
     //传入putVal之前会先计算器key的hash值
      return putVal(hash(key), key, value, false, true);
  }
//计算hash,最终会用以这个值作为tab数组的下标来存储
  //我们不直接 key.hashCode()计算hash的原因是容易出现 哈希码 与 数组大小范围不匹配的情况,即 计算出来的哈希码可能 不在数组大小范围内,从而导致无法匹配存储位置。所以我们通过[ 哈希码 与运算(&) (数组长度-1)],根据HashMap的容量大小(数组长度),按需取 哈希码一定数量的低位 作为存储的数组下标位置,从而 解决 “哈希码与数组大小范围不匹配” 的问题
   static final int hash(Object key) {
        int h;
        //扰动处理:加大哈希码低位的随机性,使得分布更均匀,从而提高对应数组存储下标位置的随机性 & 均匀性,最终减少Hash冲突
        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;
        //tab为空的话,通过resize()初始化或者扩容。
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //如果存入的当前元素的位置为空,直接tab插入元素    
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        //否则存在hash冲突    
        else {
            Node<K,V> e; K k;
            //p:tab[i]的hash与传入插入元素key一致,e记住table[i]的值,最后用新值覆盖
            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 {
               //否则链表形式存储,binCount记录链表大小,超过8树形化
                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里首先进行  if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) 的判断,只有键值对数量大于 64 才会发生转换。
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //tab大小比扩容阈值大,进行扩容。
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
//扩容 :该函数有2种使用情况:1.初始化哈希表 2.当前数组容量过小,需扩容
 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
        }
        //初始化哈希表(采用指定 or 默认值)
        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);
        }
        // 计算新的resize上限
        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) {
        // 把每个bucket都移动到新的bucket中
            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;
    }

猜你喜欢

转载自blog.csdn.net/qq_36866808/article/details/80568406
今日推荐