首页 > 编程语言 >HashMap源码分析:如何实现一次put方法

HashMap源码分析:如何实现一次put方法

时间:2024-09-21 17:15:07浏览次数:1  
标签:Node hash HashMap int value 源码 key put null

前情提示:&为按位与运算,将两个数转为二进制,当他们对应位置都为1的时候,得到的结果为,其他情况下结果为0

例如:

0000 0000 0000 1011 --->11

0000 0000 0000 1001 --->9

0000 0000 0000 1001 --->9

即11&9=9

 

本篇主要介绍hashMap的构造方法、put方法相关内容

相关成员变量介绍

    /**
     * 默认初始容量 - 必须是 2 的幂。
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
  /** * 在 constructor 中未指定 None 时使用的载荷系数。 */ static final float DEFAULT_LOAD_FACTOR = 0.75f;
  /**
   * 表示hashMap的最大容量,2^30,为什么不是2^31-1,因为还需要留出一定空间来进行检测,实际上当容量到这个量级的时候性能就已经相当差了
   */
  static final int MAXIMUM_CAPACITY = 1 << 30;
  /**
     * 当链表数量到达阈值时,会转变为红黑树。
     */
  static final int TREEIFY_THRESHOLD = 8;
  /**
     * 扩容后,当红黑树数量小于阈值时,会退化回链表。
     */
  static final int UNTREEIFY_THRESHOLD = 6;
  /**
     * 只有当bucket容量超过这个值才会发生红黑树的转换,否则即使链表达到阈值也不会转换为红黑树。
     */
  static final int MIN_TREEIFY_CAPACITY = 64;
  /**
     * HashMap的具体节点,用于大多数条目。由key计算的hash,这里还有相关的getset方法,重写的toString,equals以及hashCode
   * 值得注意的是,这里的set方法返回的是V,value=newV; */
  static class Node<K,V> implements Map.Entry<K,V> {
  final int hash;
  final K key;
   V value;
   Node<K,V> next;
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}

}

初始化的构造方法(这里的默认初始容量为16,负载因子为0.75,一旦容器超过16*0.75,就会引起容器扩容。扩容后容器容量为16*2=32)

   //构造一个具有默认初始容量 (16) 和默认负载因子 (0.75) 的空 HashMap 
public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted }

只创建了对象,没有构造初始化数组Node

 

put方法:

人话:

第一次添加的时候需要先resize扩容一下bucket,再根据key算索引然后添加。之后每次添加都是先根据key算索引,如果当前bucket[i]是空那么就可以直接插入;非空需要判断key是否存在,存在则覆盖,不存在则继续判断bucket[i]属于链表还是红黑树,再插入,如果是链表还需要在插入后判断能不能转成红黑树。插入完值之后会判断当前是不是到了容量的阈值,到了还需要去resize扩容一下。

源码:

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    /**
     * Implements Map.put and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    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 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length;
     //判断p的hash值在tab中是否存在,不存在则直接插入即可 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null);
     //p的hash值存在于table中 else { Node<K,V> e; K k;
       //判断为更新操作,将p值内容赋给e if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p;
       //判断为非更新操作,此时p是红黑树,直接插入红黑树即可 else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
       //判断为非更新并且p是链表,此时需要遍历链表,将数据插入到链表的最后位置,并且如果节点数大于规定的最大链表节点数,会将链表转换为红黑树 else { 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(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } }
       //e存在,则需要覆盖并返回旧值 if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount;
     //添加完成后看看是否需要数组扩容 if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }

流程图:

 

 

 

resize()方法

人话:

第一次扩容的时候直接使用默认的16,12创建新bucket即可。

之后每次扩容都是创新一个新的扩大一倍的bucket,遍历旧bucket。如果旧bucket中没有哈希冲突的节点,直接添加新bucket;如果是红黑树,则直接执行红黑树添加;如果是链表,则需要判断链表的节点的hash和oldCap的&运算是不是0,不是的话就可以插入后面新增的节点。

流程图:

源码:

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

 

标签:Node,hash,HashMap,int,value,源码,key,put,null
From: https://www.cnblogs.com/kun1790051360/p/18424245

相关文章