1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| 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是否未初始化或长度为0,如果是就扩容 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; //判断哈希,键是否相等 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 { //循环遍历链表 for (int binCount = 0; ; ++binCount) { //插入链表的尾部 if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); //判断是否要将链表转换为红黑树 if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); break; } //判断节点的hash和key是否相等 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; }
|