HashMap key使用注意事项 key“存在“却获取不到原因
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HashMap key使用注意事项 key“存在“却获取不到原因相关的知识,希望对你有一定的参考价值。
参考技术A 存在对应的key却获取不到的原因有可以如果是对象的话,记得查看对象hash方法是否满足自己业务,因为key是取对象hash值来进行存储的。
key的开始跟结束存在空格
key的开头为\uFEFF 字符,正常是看不出来的,debug模式看key字符串的value才能看出来 :
这个\uFEFF到底是个啥???叫做BOM。
BOM(Byte Order Mark),字节顺序标记,出现在文本文件头部,Unicode编码标准中用于标识文件是采用哪种格式的编码,但它对于文件的读者来说是不可见字符。
BOM定义:http://www.unicode.org/unicode/faq/utf_bom.html
因为Unicode可以采用16位或者32位编码,所以计算机在处理时需要知道其字节顺序,BOM就是用来标识字节流的字节顺序的,但字节顺序这个 概念对UTF-8来说是没有意义的,所以BOM对UTF-8同样没有意义。但Unicode标准BOM在UTF-8编码格式中存在,其存在位置在文件开 头,以三个字节0xEF, 0xBB, 0xBF表示。
UTF-8编码不推荐使用无意义的BOM,但许多Windows程序却在保存UTF-8编码的文件时将其存为带BOM的格式(即在文件开头加上0xEFBBBF三个字节),这么干的就包括Windows记事本。
因此,在编辑UTF-8的文件时,建议不要使用记事本等进行编辑,虽然保存后的文件仍然是UTF-8,但却已经不再是保存前的UTF-8了。
解决方法:可以使用hutool封装的BOMInputStream来去除bom。
框架---hashMap
简述:
HashMap也是我们使用非常多的Collection,它是基于哈希表的 Map 接口的实现,以key-value的形式存在。在HashMap中,key-value总是会当做一个整体来处理,系统会根据hash算法来来计算key-value的存储位置,我们总是可以通过key快速地存、取value。
一、定义
HashMap实现了Map接口,继承AbstractMap。其中Map接口定义了键映射到值的规则,而AbstractMap类提供 Map 接口的骨干实现,以最大限度地减少实现此接口所需的工作,其实AbstractMap类已经实现了Map,这里标注Map
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { }
二、构造函数
HashMap提供了三个构造函数:
HashMap():构造一个具有默认初始容量 (16) 和默认加载因子 (0.75) 的空 HashMap。
HashMap(int initialCapacity):构造一个带指定初始容量和默认加载因子 (0.75) 的空 HashMap。
HashMap(int initialCapacity, float loadFactor):构造一个带指定初始容量和加载因子的空 HashMap。
这里提到了两个参数:初始容量,加载因子。这两个参数是影响HashMap性能的重要参数,其中容量表示哈希表中桶的数量,初始容量是创建哈希表时的容量,加载因子是哈希表在其容量自动增加之前可以达到多满的一种尺度,它衡量的是一个散列表的空间的使用程度,负载因子越大表示散列表的装填程度越高,反之愈小。对于使用链表法的散列表来说,查找一个元素的平均时间是O(1+a),因此如果负载因子越大,对空间的利用更充分,然而后果是查找效率的降低;如果负载因子太小,那么散列表的数据将过于稀疏,对空间造成严重浪费。系统默认负载因子为0.75,一般情况下我们是无需修改的。
HashMap是一种支持快速存取的数据结构,要了解它的性能必须要了解它的数据结构。
三、数据结构
我们知道在Java中最常用的两种结构是数组和模拟指针(引用),几乎所有的数据结构都可以利用这两种来组合实现,HashMap也是如此。实际上HashMap是一个“链表散列”.
JDK1.6实现hashmap的方式是采用位桶(数组)+链表的方式,即散列链表方式。
JDK1.8则是采用位桶+链表/红黑树的方式,即当某个位桶的链表长度达到某个阈值(8)的时候,这个链表就转化成红黑树,这样大大减少了查找时间。
/** * 带俩参数构造方法 * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is negative * or the load factor is nonpositive */ public HashMap(int initialCapacity, float loadFactor) { //初始化容量不能小于0,否者抛出异常 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; this.threshold = tableSizeFor(initialCapacity); }
一个内部实现类Node
/** *相比于之前的版本,jdk1.8在解决哈希冲突时有了较大的变化,当链表长度大于阈值(默认为8)时,将链表转化为红黑树,以减少搜索时间。 *原本Map.Entry接口的实现类Entry改名为了Node。转化为红黑树时改用另一种实现TreeNode */ 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; } //重写hashCode方法 public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } //重写equals方法 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; } }
Node类实现了Map.Entry接口,是HashMap内部的一种数据结构,主要是键值对组成,是一个对象结点,它包含了键key、值value、下一个节点next,以及hash值,HashMap可以想象成一个table数组,而数组中存放的元素是Node<k,v>对象对应的地址。HashMap根据对Node对象的key值进行hash获取hash地址,然后找到相应的hash地址,如果有发生哈希冲突,则将该对象元素存入链表中,当链表元素个数达到一定要求,则将链表结构转化为红黑树。
四、存储实现
1).put方法
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
2)hash(key)方法
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
2.1) 看出key是可以空的 返回值为0
2.2)(h = key.hashCode()) ^ (h >>> 16)
第一步取key的hashcode值
第二步 高位参与运算 h ^ (h >>> 16)
这里这么干是出于性能考虑,底层的移位和异或运算肯定比加减乘除取模等效率好
hashcode是32位的,无符号右移16位,那生成的就是16位0加原高位的16位值, 就是对半了,异或计算也就变成了高16位和低16位进行异或,原高16位不变。这么干主要用于当hashmap 数组比较小的时候所有bit都参与运算了,防止hash冲突太大,
所谓hash冲突是指不同的key计算出的hash是一样的,比如a和97,这个肯定是存在的没毛病
3)putVal()方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) { //申明变量,Node是一个内部类 Node<K,V>[] tab; Node<K,V> p; int n, i; //tab = table赋值,table现在是null的,so n = tab.length不运行了 运行这个if的代码块 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; //再看就知道了判断当前存的key计算出的索引位置是不是已经存过值了 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null //前存的key计算出的索引位置有值,其实就意味着发生hash冲突了 比如key分别是a和97 hashCode都是97 冲突 else { Node<K,V> e; K k; //再看就知道了判断当前存的key计算出的索引位置是不是已经存过值了 //1.存过值了首先重新判断hash值是否一样,然后key分别判断是否key值一样,此处用equals方法 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; //2.判断原来元素是不是 TreeNode(红黑树) 类型,TreeNode一样是静态内部类 else if (p instanceof TreeNode) // putTreeVal 向红黑树中添加元素内部实现,存在相同key就返回赋值给e 不存在就添加并返回null 源码就是红黑树算法 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); //3.key不同也不是红黑树--- else { //明显的链表啊--整个循环,明显是在从头开始遍历链表,找到相同key或链表找完了新元素挂链表最后 for (int binCount = 0; ; ++binCount) { //这是在链表找完了,且新元素已经挂在链表最后了有的一个判断 if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); //判断循环次数,其实就是链表长度,长度超过TREEIFY_THRESHOLD 默认8则运行treeifyBin(tab, hash); 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; } } //4.最后判断e是不是空,上面的冲突方案看出e不是空就是表示有相同的key,进行value覆盖就可以,e空就是无相同key且完成了数据挂载 if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; //resize 再详走 putVal最后一段size>threshold if (++size > threshold) //threshold初始12 ++size元素数量肯定会有超12个的时候,这里也就看出了threshold代表HashMap的容量,到上限就要扩容了,默认现在16数组,12元素上限 resize(); afterNodeInsertion(evict); return null; }
4)Node<K,V>内部类
/** *相比于之前的版本,jdk1.8在解决哈希冲突时有了较大的变化,当链表长度大于阈值(默认为8)时,将链表转化为红黑树,以减少搜索时间。 *原本Map.Entry接口的实现类Entry改名为了Node。转化为红黑树时改用另一种实现TreeNode * *Node是内部的一个静态类 *是一个带有3个值,hash、key、value和另一个Node对象引用的HashMap子元素结构,即我们装的每个键值对就用一个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; } }
5).resize()方法
/** * 对table进行初始化或者扩容 * 如果table为null,则对table进行初始化 * 如果对table扩容,因为每次扩容都是翻倍,与原来计算(n-1)&hash的结果相比,节点要么就在原来的位置,要么就被分配到“原位置+旧容量”这个位置 * resize的步骤总结为: * 1.计算扩容后的容量,临界值。 * 2.将hashMap的临界值修改为扩容后的临界值 * 3.根据扩容后的容量新建数组,然后将hashMap的table的引用指向新数组。 * 4.将旧数组的元素复制到table中。 * @return the table */ final Node<K,V>[] resize() { //新建oldTab数组保存扩容前的数组table Node<K,V>[] oldTab = table; //获取原来数组的长度 int oldCap = (oldTab == null) ? 0 : oldTab.length; //原来数组扩容的临界值 int oldThr = threshold; int newCap, newThr = 0; //如果扩容前的容量 > 0 if (oldCap > 0) { //如果原来的数组长度大于最大值(2^30) if (oldCap >= MAXIMUM_CAPACITY) { //扩容临界值提高到正无穷 threshold = Integer.MAX_VALUE; //无法进行扩容,返回原来的数组 return oldTab; //如果现在容量的两倍小于MAXIMUM_CAPACITY且现在的容量大于DEFAULT_INITIAL_CAPACITY } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) //临界值变为原来的2倍 newThr = oldThr << 1; // double threshold } else if (oldThr > 0) //如果旧容量 <= 0,而且旧临界值 > 0 //数组的新容量设置为老数组扩容的临界值 newCap = oldThr; else { //如果旧容量 <= 0,且旧临界值 <= 0,新容量扩充为默认初始化容量,新临界值为DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY newCap = DEFAULT_INITIAL_CAPACITY;//新数组初始容量设置为默认值 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//计算默认容量下的阈值 } // 计算新的resize上限 if (newThr == 0) {//在当上面的条件判断中,只有oldThr > 0成立时,newThr == 0 //ft为临时临界值,下面会确定这个临界值是否合法,如果合法,那就是真正的临界值 float ft = (float)newCap * loadFactor; //当新容量< MAXIMUM_CAPACITY且ft < (float)MAXIMUM_CAPACITY,新的临界值为ft,否则为Integer.MAX_VALUE newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } //将扩容后hashMap的临界值设置为newThr threshold = newThr; @SuppressWarnings({"rawtypes","unchecked"}) //创建新的table,初始化容量为newCap Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; //修改hashMap的table为新建的newTab table = newTab; //如果旧table不为空,将旧table中的元素复制到新的table中 if (oldTab != null) { //遍历旧哈希表的每个桶,将旧哈希表中的桶复制到新的哈希表中 for (int j = 0; j < oldCap; ++j) { Node<K,V> e; //如果旧桶不为null,使用e记录旧桶 if ((e = oldTab[j]) != null) { //将旧桶置为null oldTab[j] = null; //如果旧桶中只有一个node if (e.next == null) //将e也就是oldTab[j]放入newTab中e.hash & (newCap - 1)的位置 newTab[e.hash & (newCap - 1)] = e; //如果旧桶中的结构为红黑树 else if (e instanceof TreeNode) //将树中的node分离 ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { //如果旧桶中的结构为链表,链表重排,jdk1.8做的一系列优化 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 {// 原索引+oldCap if (hiTail == null) hiHead = e; else hiTail.next = e; hiTail = e; } } while ((e = next) != null); // 原索引放到bucket里 if (loTail != null) { loTail.next = null; newTab[j] = loHead; } // 原索引+oldCap放到bucket里 if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab; }
存储查找原理:
存储:首先获取key的hashcode,然后取模数组的长度,这样可以快速定位到要存储到数组中的坐标,然后判断数组中是否存储元素,如果没有存储则,新构建Node节点,把Node节点存储到数组中,如果有元素,则迭代链表(红黑二叉树),如果存在此key,默认更新value,不存在则把新构建的Node存储到链表的尾部。查找:同上,获取key的hashcode,通过hashcode取模数组的长度,获取要定位元素的坐标,然后迭代链表,进行每一个元素的key的equals对比,如果相同则返回该元素。
HashMap在相同元素个数时,数组的长度越大,则Hash的碰撞率越低,则读取的效率就越高,数组长度越小,则碰撞率高,读取速度就越慢。典型的空间换时间的例子。
问题:
1、hash取余数,为什么不用取模操作呢,而用tab[i = (n - 1) & hash]?
它通过 (n - 1) & hash来得到该对象的保存位,而HashMap底层数组的长度总是2的n次方,这是HashMap在速度上的优化。当length总是2的n次方时, (n - 1) & hash运算等价于对length取模,也就是h%length,但是&比%具有更高的效率。
2、为什么使用红黑二叉树呢?
因为在好的算法,也避免不了hash的碰撞,避免不了链表过长的的情况,一旦出现链表过长,则严重影响到HashMap的性能。JDK8对HashMap做了优化,把链表长度超过8个的,则改成红黑二叉树,提高访问的速度。
完整的源码:
package java.util; import java.io.IOException; import java.io.InvalidObjectException; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; /** * * @param <K> the type of keys maintained by this map * @param <V> the type of mapped values * * @author Doug Lea * @author Josh Bloch * @author Arthur van Hoff * @author Neal Gafter * @see Object#hashCode() * @see Collection * @see Map * @see TreeMap * @see Hashtable * @since 1.2 */ public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { private static final long serialVersionUID = 362498820763181265L; /** * 默认初始化容量 * 1的二进制表示 0001 * 1 << 4即1左移4位 1000 即等于 2^4 * 且实际容量必须是2的整数次幂 */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //2^4=16 /** * 初始化最大容量 * 1的二进制表示 0000 0000 0000 0000 0000 0000 0000 0001 * 1 << 30即1左移30位 0010 0000 0000 0000 0000 0000 0000 0000 即等于2^30= * 必须是2的幂且小于2的30次方,传入容量过大将被这个值替换 * */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * 加载因子,默认值为0.75f---浮点型 */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** *JDK1.8 新加 * 一个桶的树化阈值即Node链表最大长度 * 当桶中元素个数超过这个值时,需要使用红黑树节点替换链表节点 * 这个值必须为 8,要不然频繁转换效率也不高 */ static final int TREEIFY_THRESHOLD = 8; /** * JDK1.8 新加 * 一个树的链表还原阈值 * 当扩容时,桶中元素个数小于这个值,就会把树形的桶元素 还原(切分)为链表结构 * 这个值应该比上面那个小,至少为 6,避免频繁转换 */ static final int UNTREEIFY_THRESHOLD = 6; /** * 哈希表的最小树形化容量 * 当哈希表中的容量大于这个值时,表中的桶才能进行树形化 * 否则桶内元素太多时会扩容,而不是树形化 * 为了避免进行扩容、树形化选择的冲突,这个值不能小于 4 * TREEIFY_THRESHOLDlds. */ static final int MIN_TREEIFY_CAPACITY = 64; /** *相比于之前的版本,jdk1.8在解决哈希冲突时有了较大的变化,当链表长度大于阈值(默认为8)时,将链表转化为红黑树,以减少搜索时间。 *原本Map.Entry接口的实现类Entry改名为了Node。转化为红黑树时改用另一种实现TreeNode */ 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; } //重写hashCode方法 public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } //重写equals方法 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; } } /* ---------------- Static utilities -------------- */ /** *HashMap中键值对的存储形式为链表节点,hashCode相同的节点(位于同一个桶)用链表组织 *hash方法分为三步: *1.取key的hashCode *2.key的hashCode高16位异或低16位 *3.将第一步和第二步得到的结果进行取模运算。 */ static final int hash(Object key) { int h; //key都等于空的时候 hash值返回0,否则返回hash算法算出的hash值 ////计算key的hashCode, h = Objects.hashCode(key) return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } /** * 如果参数x实现了Comparable接口,返回参数x的类名,否则返回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; } /** * 如果x的类型为kc,则返回k.compareTo(x),否则返回0 * */ @SuppressWarnings({"rawtypes","unchecked"}) static int compareComparables(Class<?> kc, Object k, Object x) { return (x == null || x.getClass() != kc ? 0 : ((Comparable)k).compareTo(x)); } /** * 结果为>=cap的最小2的自然数幂 */ static final int tableSizeFor(int cap) { int n = cap - 1; //先移位再或运算,最终保证返回值是2的整数幂 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; } /* ---------------- Fields -------------- */ /** * 存储数据的Node数组,分配的时候,table的长度总是2的幂 */ transient Node<K,V>[] table; /** * 返回Map中所包含的Map.Entry<K,V>的Set视图 *HashMap将数据转换成set的另一种存储形式,这个变量主要用于迭代功能 */ transient Set<Map.Entry<K,V>> entrySet; /** * 当前存储元素的总个数即实际存储的数量 * HashMap的size()方法,实际返回的就是这个值,isEmpty()也是判断该值是否为0 */ transient int size; /** *HashMap内部结构发生变化的次数,主要用于迭代的快速失败======>fail-fast机制 */ transient int modCount; /** * 下次扩容的临界值,size>=threshold就会扩容, * jdk1.8前 threshold等于capacity*load factor * jdk1.8对threshold值进行了改进,通过一系列位移操作算法最后得到一个power of two size的值, * HashMap的扩容阈值,在HashMap中存储的Node键值对超过这个数量时,自动扩容容量为原来的二倍 */ int threshold; /** * * HashMap的负加载因子,可计算出当前table长度下的扩容阈值:threshold = loadFactor * table.length * @serial */ final float loadFactor; /* ---------------- Public operations -------------- */ /** * 带俩参数构造方法 * @param initialCapacity the initial capacity 初始化容量 * @param loadFactor the load factor 加载因子 * @throws IllegalArgumentException if the initial capacity is negative * or the load factor is nonpositive如果指定的初始化容量为负数或者加载因子为非正数 */ public HashMap(int initialCapacity, float loadFactor) { //初始化容量不能小于0,否者抛出异常 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; //在jdk1.7及以前,threshold = capacity * loadFactor,其中 capacity 为桶数组的长度 //jdk1.8对threshold值进行了改进,通过一系列位移操作算法最后得到一个power of two size的值, this.threshold = tableSizeFor(initialCapacity); } /** * 带一个初始化容量参数的构造方法,默认加载因子为0.75 */ public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } /** * 不带参数的构造方法,默认加载因子为0.75 */ public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; } /** * 使用指定Map m构造新的HashMap。 * 使用指定的初始化容量(16)和默认加载因子DEFAULT_LOAD_FACTOR(0.75) * @param m the map whose mappings are to be placed in this map * @throws NullPointerException if the specified map is null */ public HashMap(Map<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); } /** * Map.putAll and Map constructor的实现需要的方法 * 将m的键值对插入本map中 * @param m the map 指定的map * @param evict false when initially constructing this map, else * true (relayed to method afterNodeInsertion). 初始化map时使用false,否则使用true */ final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) { int s = m.size(); //如果参数map不为空 if (s > 0) { //判断table是否已经初始化 if (table == null) { // pre-size //未初始化,s为m的实际元素个数 float ft = ((float)s / loadFactor) + 1.0F; int t = ((ft < (float)MAXIMUM_CAPACITY) ? (int)ft : MAXIMUM_CAPACITY); // 计算得到的t大于阈值,则初始化阈值 if (t > threshold) //根据容量初始化临界值 threshold = tableSizeFor(t); } // 已初始化,并且m元素个数大于阈值,进行扩容处理 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); } } } /** * 返回map中键值对映射的个数 * * @return the number of key-value mappings in this map */ public int size() { return size; } /** * 如果map中没有键值对映射,返回true * * @return <tt>true</tt> if this map contains no key-value mappings */ public boolean isEmpty() { return size == 0; } /** *返回指定的key映射的value,如果value为null,则返回nul *get可以分为三个步骤: *1.通过hash(Object key)方法计算key的哈希值hash。 *2.通过getNode( int hash, Object key)方法获取node。 *3.如果node为null,返回null,否则返回node.value。 */ public V get(Object key) { Node<K,V> e; //根据key及其hash值查询node节点,如果存在,则返回该节点的value值 return (e = getNode(hash(key), key)) == null ? null : e.value; } /** * 根据key的哈希值和key获取对应的节点 *getNode可分为以下几个步骤: *1.如果哈希表为空,或key对应的桶为空,返回null *2.如果桶中的第一个节点就和指定参数hash和key匹配上了,返回这个节点 *3.如果桶中的第一个节点没有匹配上,而且有后续节点 *3.1如果当前的桶采用红黑树,则调用红黑树的get方法去获取节点 *3.2如果当前的桶不采用红黑树,即桶中节点结构为链式结构,遍历链表,直到key匹配 *4.找到节点返回null,否则返回null。 * @param hash hash for key * @param key the key * @return the node, or null if none */ final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; //&运算时均把运算数转换为二进制再做比较,规则:当相同的位上均为1时结果为1,否则结 果为0. ////如果哈希表不为空,而且key对应的桶上不为空 if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { //如果桶中的第一个节点就和指定参数hash和key匹配上了 if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k)))) return first; //如果桶中的第一个节点没有匹配上,而且有后续节点 if ((e = first.next) != null) { //如果当前的桶采用红黑树,则调用红黑树的get方法去获取节点 if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); //如果当前的桶不采用红黑树,即桶中节点结构为链式结构 do { ////遍历链表,直到key匹配 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } //如果哈希表为空,或者没有找到节点,返回null return null; } /** *如果map中含有key为指定参数key的键值对,返回true * * @param key The key whose presence in this map is to be tested * @return <tt>true</tt> if this map contains a mapping for the specified * key. */ public boolean containsKey(Object key) { return getNode(hash(key), key) != null; } /** *将指定参数key和指定参数value插入map中,如果key已经存在,那就替换key对应的valu * put(K key, V value)可以分为三个步骤: *1.通过hash(Object key)方法计算key的哈希值。 *2.通过putVal(hash(key), key, value, false, true)方法实现功能 *3.返回putVal方法返回的结果。 * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>.) */ public V put(K key, V value) { // 倒数第二个参数false:表示允许旧值替换 // 最后一个参数true:表示HashMap不处于创建模式 return putVal(hash(key), key, value, false, true); } /** * Map.put和其他相关方法的实现需要的方法 * putVal方法可以分为下面的几个步骤: *1.如果哈希表为空,调用resize()创建一个哈希表。 *2.如果指定参数hash在表中没有对应的桶,即为没有碰撞,直接将键值对插入到哈希表中即可。 *3.如果有碰撞,遍历桶,找到key映射的节点 * 3.1桶中的第一个节点就匹配了,将桶中的第一个节点记录起来。 * 3.2如果桶中的第一个节点没有匹配,且桶中结构为红黑树,则调用红黑树对应的方法插入键值对。 * 3.3如果不是红黑树,那么就肯定是链表。遍历链表,如果找到了key映射的节点,就记录这个节点,退出循环。如果没有找到,在链表尾部插入节点。 * 插入后,如果链的长度大于TREEIFY_THRESHOLD这个临界值,则使用treeifyBin方法把链表转为红黑树。 *4.如果找到了key映射的节点,且节点不为null * 4.1记录节点的vlaue。 * 4.2如果参数onlyIfAbsent为false,或者oldValue为null,替换value,否则不替换 * 4.3返回记录下来的节点的value。 * 5.如果没有找到key映射的节点(2、3步中讲了,这种情况会插入到hashMap中),插入节点后size会加1,这时要检查size是否大于临界值threshold,如果大于会使用resize方法进行扩容。 * @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; if ((tab = table) == null || (n = tab.length) == 0) //如果哈希表为空,调用resize()创建一个哈希表,并用变量n记录哈希表长度 n = (tab = resize()).length; //如果指定参数hash在表中没有对应的桶,即为没有碰撞 //Hash函数,(n - 1) & hash 计算key将被放置的槽位 //(n - 1) & hash 本质上是hash % n,位运算更快 if ((p = tab[i = (n - 1) & hash]) == null) //直接将键值对插入到map中即可 tab[i] = newNode(hash, key, value, null); else { // 桶中已经存在元素 Node<K,V> e; K k; // 比较桶中第一个元素(数组中的结点)的hash值相等,key相等 if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k)))) // 将第一个元素赋值给e,用e来记录 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) // -1 for 1st treeifyBin(tab, hash); break; } // 链表节点的<key, value>与put操作<key, value>相同时,不做重复操作,跳出循环 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } // 找到或新建一个key和hashCode与插入元素相等的键值对,进行put操作 if (e != null) { // existing mapping for key // 记录e的value V oldValue = e.value; //onlyIfAbsent为false或旧值为null时,允许替换旧值否则无需替换 if (!onlyIfAbsent || oldValue == null) e.value = value; // 访问后回调 afterNodeAccess(e); // 返回旧值 return oldValue; } } // 更新结构化修改信息 ++modCount; // 键值对数目超过阈值时,进行rehash if (++size > threshold) resize(); // 插入后回调 afterNodeInsertion(evict); return null; } /** * 对table进行初始化或者扩容 * 如果table为null,则对table进行初始化 * 如果对table扩容,因为每次扩容都是翻倍,与原来计算(n-1)&hash的结果相比,节点要么就在原来的位置,要么就被分配到“原位置+旧容量”这个位置 * resize的步骤总结为: * 1.计算扩容后的容量,临界值。 * 2.将hashMap的临界值修改为扩容后的临界值 * 3.根据扩容后的容量新建数组,然后将hashMap的table的引用指向新数组。 * 4.将旧数组的元素复制到table中。 * @return the table */ final Node<K,V>[] resize() { //新建oldTab数组保存扩容前的数组table Node<K,V>[] oldTab = table; //获取原来数组的长度 int oldCap = (oldTab == null) ? 0 : oldTab.length; //原来数组扩容的临界值 int oldThr = threshold; int newCap, newThr = 0; //如果扩容前的容量 > 0 if (oldCap > 0) { //如果原来的数组长度大于最大值(2^30) if (oldCap >= MAXIMUM_CAPACITY) { //扩容临界值提高到正无穷 threshold = Integer.MAX_VALUE; //无法进行扩容,返回原来的数组 return oldTab; //如果现在容量的两倍小于MAXIMUM_CAPACITY且现在的容量大于DEFAULT_INITIAL_CAPACITY } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) //临界值变为原来的2倍 newThr = oldThr << 1; // double threshold } else if (oldThr > 0) //如果旧容量 <= 0,而且旧临界值 > 0 //数组的新容量设置为老数组扩容的临界值 newCap = oldThr; else { //如果旧容量 <= 0,且旧临界值 <= 0,新容量扩充为默认初始化容量,新临界值为DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY newCap = DEFAULT_INITIAL_CAPACITY;//新数组初始容量设置为默认值 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//计算默认容量下的阈值 } // 计算新的resize上限 if (newThr == 0) {//在当上面的条件判断中,只有oldThr > 0成立时,newThr == 0 //ft为临时临界值,下面会确定这个临界值是否合法,如果合法,那就是真正的临界值 float ft = (float)newCap * loadFactor; //当新容量< MAXIMUM_CAPACITY且ft < (float)MAXIMUM_CAPACITY,新的临界值为ft,否则为Integer.MAX_VALUE newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } //将扩容后hashMap的临界值设置为newThr threshold = newThr; @SuppressWarnings({"rawtypes","unchecked"}) //创建新的table,初始化容量为newCap Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; //修改hashMap的table为新建的newTab table = newTab; //如果旧table不为空,将旧table中的元素复制到新的table中 if (oldTab != null) { //遍历旧哈希表的每个桶,将旧哈希表中的桶复制到新的哈希表中 for (int j = 0; j < oldCap; ++j) { Node<K,V> e; //如果旧桶不为null,使用e记录旧桶 if ((e = oldTab[j]) != null) { //将旧桶置为null oldTab[j] = null; //如果旧桶中只有一个node if (e.next == null) //将e也就是oldTab[j]放入newTab中e.hash & (newCap - 1)的位置 newTab[e.hash & (newCap - 1)] = e; //如果旧桶中的结构为红黑树 else if (e instanceof TreeNode) //将树中的node分离 ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { //如果旧桶中的结构为链表,链表重排,jdk1.8做的一系列优化 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 {// 原索引+oldCap if (hiTail == null) hiHead = e; else hiTail.next = e; hiTail = e; } } while ((e = next) != null); // 原索引放到bucket里 if (loTail != null) { loTail.next = null; newTab[j] = loHead; } // 原索引+oldCap放到bucket里 if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab; } /** * 将链表转化为红黑树 * */ final void treeifyBin(Node<K,V>[] tab, int hash) { int n, index; Node<K,V> e; //如果桶数组table为空,或者桶数组table的长度小于MIN_TREEIFY_CAPACITY,不符合转化为红黑树的条件 if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize(); //如果符合转化为红黑树的条件,而且hash对应的桶不为null else if ((e = tab[index = (n - 1) & hash]) != null) { // 红黑树的头、尾节点 TreeNode<K,V> hd = null, tl = null; //遍历链表 do { //替换链表node为树node,建立双向链表 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); } } /** *将参数map中的所有键值对映射插入到hashMap中,如果有碰撞,则覆盖value。 * * @param m mappings to be stored in this map * @throws NullPointerException if the specified map is null */ public void putAll(Map<? extends K, ? extends V> m) { putMapEntries(m, true); } /** * 删除hashMap中key映射的node *remove方法的实现可以分为三个步骤: * 1.通过 hash(Object key)方法计算key的哈希值 * 2.通过 removeNode 方法实现功能。 * 3.返回被删除的node的value。 * */ public V remove(Object key) { Node<K,V> e; //根据key来删除node。removeNode方法的具体实现在下面 return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value; } /** * Map.remove和相关方法的实现需要的方法 * removeNode方法的步骤总结为: * 1.如果数组table为空或key映射到的桶为空,返回null。 * 2.如果key映射到的桶上第一个node的就是要删除的node,记录下来。 * 3.如果桶内不止一个node,且桶内的结构为红黑树,记录key映射到的node。 * 4.桶内的结构不为红黑树,那么桶内的结构就肯定为链表,遍历链表,找到key映射到的node,记录下来。 * 5.如果被记录下来的node不为null,删除node,size-1被删除。 * 6.返回被删除的node。 */ 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不为空且key映射到的桶不为空 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; //如果桶上第一个node的就是要删除的node if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k)))) //记录桶上第一个node node = p; else if ((e = p.next) != null) {//如果桶内不止一个node //如果桶内的结构为红黑树 if (p instanceof TreeNode) //记录key映射到的node node = ((TreeNode<K,V>)p).getTreeNode(hash, key); else { //如果桶内的结构为链表 do { //遍历链表,找到key映射到的node if (e.hash == hash &&((k = e.key) == key ||(key != null && key.equals(k)))) { //记录key映射到的node node = e; break; } p = e; } while ((e = e.next) != null); } } //如果得到的node不为null且(matchValue为false||node.value和参数value匹配) if (node != null && (!matchValue || (v = node.value) == value ||(value != null && value.equals(v)))) { //如果桶内的结构为红黑树 if (node instanceof TreeNode) // 使用红黑树的删除方法删除node ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable); else if (node == p)//如果桶的第一个node的就是要删除的node //删除node tab[index] = node.next; else //如果桶内的结构为链表,使用链表删除元素的方式删除node p.next = node.next; ++modCount;//结构性修改次数+1 --size;//哈希表大小-1 afterNodeRemoval(node); return node;//返回被删除的node } } return null;//如果数组table为空或key映射到的桶为空,返回null。 } /** * 删除map中所有的键值对 * */ public void clear() { Node<K,V>[] tab; modCount++; if ((tab = table) != null && size > 0) { size = 0; for (int i = 0; i < tab.length; ++i) tab[i] = null; } } /** * 如果hashMap中的键值对有一对或多对的value为参数value,返回true * * @param value value whose presence in this map is to be tested * @return <tt>true</tt> if this map maps one or more keys to the * specified value */ public boolean containsValue(Object value) { Node<K,V>[] tab; V v; if ((tab = table) != null && size > 0) { //遍历数组table for (int i = 0; i < tab.length; ++i) { //遍历桶中的node 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; } /** * 返回hashMap中所有key的视图。 * 改变hashMap会影响到set,反之亦然。 * 如果当迭代器迭代set时,hashMap被修改(除非是迭代器自己的remove()方法),迭代器的结果是不确定的。 * set支持元素的删除,通过Iterator.remove、Set.remove、removeAll、retainAll、clear操作删除hashMap中对应的键值对。 * 不支持add和addAll方法。 * * @return a set view of the keys contained in this map */ public Set<K> keySet() { Set<K> ks = keySet; if (ks == null) { ks = new KeySet(); keySet = ks; } return ks; } /** * 内部类KeySet */ final class KeySet extends AbstractSet<K> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator<K> iterator() { return new KeyIterator(); } public final boolean contains(Object o) { return containsKey(o); } public final boolean remove(Object key) { return removeNode(hash(key), key, null, false, true) != null; } public final Spliterator<K> spliterator() { return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0); } public final void forEach(Consumer<? super K> action) { Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) action.accept(e.key); } if (modCount != mc) throw new ConcurrentModificationException(); } } } /** * 返回hashMap中所有value的collection视图 * 改变hashMap会改变collection,反之亦然。 * 如果当迭代器迭代collection时,hashMap被修改(除非是迭代器自己的remove()方法),迭代器的结果是不确定的。 * collection支持元素的删除,通过Iterator.remove、Collection.remove、removeAll、retainAll、clear操作删除hashMap中对应的键值对。 * 不支持add和addAll方法。 * * @return a view of the values contained in this map */ public Collection<V> values() { Collection<V> vs = values; if (vs == null) { vs = new Values(); values = vs; } return vs; } /** * 内部类Values */ final class Values extends AbstractCollection<V> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator<V> iterator() { return new ValueIterator(); } public final boolean contains(Object o) { return containsValue(o); } public final Spliterator<V> spliterator() { return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0); } public final void forEach(Consumer<? super V> action) { Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) action.accept(e.value); } if (modCount != mc) throw new ConcurrentModificationException(); } } } /** * 返回hashMap中所有键值对的set视图 * 改变hashMap会影响到set,反之亦然。 * 如果当迭代器迭代set时,hashMap被修改(除非是迭代器自己的remove()方法),迭代器的结果是不确定的。 * set支持元素的删除,通过Iterator.remove、Set.remove、removeAll、retainAll、clear操作删除hashMap中对应的键值对。 * 不支持add和addAll方法。 * @return a set view of the mappings contained in this map */ public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es; return (es = entrySet) == null ? (entrySet = new EntrySet()) : es; } final class EntrySet extends AbstractSet<Map.Entry<K,V>> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator<Map.Entry<K,V>> iterator() { return new EntryIterator(); } public final boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry<?,?> e = (Map.Entry<?,?>) o; Object key = e.getKey(); Node<K,V> candidate = getNode(hash(key), key); return candidate != null && candidate.equals(e); } public final boolean remove(Object o) { if (o instanceof Map.Entry) { Map.Entry<?,?> e = (Map.Entry<?,?>) o; Object key = e.getKey(); Object value = e.getValue(); return removeNode(hash(key), key, value, true, true) != null; } return false; } public final Spliterator<Map.Entry<K,V>> spliterator() { return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0); } public final void forEach(Consumer<? super Map.Entry<K,V>> action) { Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) action.accept(e); } if (modCount != mc) throw new ConcurrentModificationException(); } } } //// JDK8重写的方法 /** *通过key映射到对应node,如果没映射到则返回默认值defaultValue * * *@param key *@param defaultValue * @return key映射到对应的node,如果没映射到则返回默认值defaultValue */ @Override public V getOrDefault(Object key, V defaultValue) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? defaultValue : e.value; } @Override public V putIfAbsent(K key, V value) { return putVal(hash(key), key, value, true, true); } @Override public boolean remove(Object key, Object value) { return removeNode(hash(key), key, value, true, true) != null; } @Override public boolean replace(K key, V oldValue, V newValue) { Node<K,V> e; V v; if ((e = getNode(hash(key), key)) != null && ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) { e.value = newValue; afterNodeAccess(e); return true; } return false; } @Override public V replace(K key, V value) { Node<K,V> e; if ((e = getNode(hash(key), key)) != null) { V oldValue = e.value; e.value = value; afterNodeAccess(e); return oldValue; } return null; } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { if (mappingFunction == null) throw new NullPointerException(); int hash = hash(key); Node<K,V>[] tab; Node<K,V> first; int n, i; int binCount = 0; TreeNode<K,V> t = null; Node<K,V> old = null; if (size > threshold || (tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((first = tab[i = (n - 1) & hash]) != null) { if (first instanceof TreeNode) old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key); else { Node<K,V> e = first; K k; do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { old = e; break; } ++binCount; } while ((e = e.next) != null); } V oldValue; if (old != null && (oldValue = old.value) != null) { afterNodeAccess(old); return oldValue; } } V v = mappingFunction.apply(key); if (v == null) { return null; } else if (old != null) { old.value = v; afterNodeAccess(old); return v; } else if (t != null) t.putTreeVal(this, tab, hash, key, v); else { tab[i] = newNode(hash, key, v, first); if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); } ++modCount; ++size; afterNodeInsertion(true); return v; } public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { if (remappingFunction == null) throw new NullPointerException(); Node<K,V> e; V oldValue; int hash = hash(key); if ((e = getNode(hash, key)) != null && (oldValue = e.value) != null) { V v = remappingFunction.apply(key, oldValue); if (v != null) { e.value = v; afterNodeAccess(e); return v; } else removeNode(hash, key, null, false, true); } return null; } @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { if (remappingFunction == null) throw new NullPointerException(); int hash = hash(key); Node<K,V>[] tab; Node<K,V> first; int n, i; int binCount = 0; TreeNode<K,V> t = null; Node<K,V> old = null; if (size > threshold || (tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((first = tab[i = (n - 1) & hash]) != null) { if (first instanceof TreeNode) old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key); else { Node<K,V> e = first; K k; do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { old = e; break; } ++binCount; } while ((e = e.next) != null); } } V oldValue = (old == null) ? null : old.value; V v = remappingFunction.apply(key, oldValue); if (old != null) { if (v != null) { old.value = v; afterNodeAccess(old); } else removeNode(hash, key, null, false, true); } else if (v != null) { if (t != null) t.putTreeVal(this, tab, hash, key, v); else { tab[i] = newNode(hash, key, v, first); if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); } ++modCount; ++size; afterNodeInsertion(true); } return v; } @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { if (value == null) throw new NullPointerException(); if (remappingFunction == null) throw new NullPointerException(); int hash = hash(key); Node<K,V>[] tab; Node<K,V> first; int n, i; int binCount = 0; TreeNode<K,V> t = null; Node<K,V> old = null; if (size > threshold || (tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; if ((first = tab[i = (n - 1) & hash]) != null) { if (first instanceof TreeNode) old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key); else { Node<K,V> e = first; K k; do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { old = e; break; } ++binCount; } while ((e = e.next) != null); } } if (old != null) { V v; if (old.value != null) v = remappingFunction.apply(old.value, value); else v = value; if (v != null) { old.value = v; afterNodeAccess(old); } else removeNode(hash, key, null, false, true); return v; } if (value != null) { if (t != null) t.putTreeVal(this, tab, hash, key, value); else { tab[i] = newNode(hash, key, value, first); if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); } ++modCount; ++size; afterNodeInsertion(true); } return value; } @Override public void forEach(BiConsumer<? super K, ? super V> action) { Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) action.accept(e.key, e.value); } if (modCount != mc) throw new ConcurrentModificationException(); } } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { Node<K,V>[] tab; if (function == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) { e.value = function.apply(e.key, e.value); } } if (modCount != mc) throw new ConcurrentModificationException(); } } /* ------------------------------------------------------------ */ // Cloning and serialization /** * Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and * values themselves are not cloned. * * @return a shallow copy of this map */ @SuppressWarnings("unchecked") @Override public Object clone() { HashMap<K,V> result; try { result = (HashMap<K,V>)super.clone(); } catch (CloneNotSupportedException e) { // this shouldn‘t happen, since we are Cloneable throw new InternalError(e); } result.reinitialize(); result.putMapEntries(this, false); return result; } // These methods are also used when serializing HashSets final float loadFactor() { return loadFactor; } final int capacity() { return (table != null) ? table.length : (threshold > 0) ? threshold : DEFAULT_INITIAL_CAPACITY; } /** * Save the state of the <tt>HashMap</tt> instance to a stream (i.e., * serialize it). * * @serialData The <i>capacity</i> of the HashMap (the length of the * bucket array) is emitted (int), followed by the * <i>size</i> (an int, the number of key-value * mappings), followed by the key (Object) and value (Object) * for each key-value mapping. The key-value mappings are * emitted in no particular order. */ private void writeObject(java.io.ObjectOutputStream s) throws IOException { int buckets = capacity(); // Write out the threshold, loadfactor, and any hidden stuff s.defaultWriteObject(); s.writeInt(buckets); s.writeInt(size); internalWriteEntries(s); } /** * Reconstitute the {@code HashMap} instance from a stream (i.e., * deserialize it). */ private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { // Read in the threshold (ignored), loadfactor, and any hidden stuff s.defaultReadObject(); reinitialize(); if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new InvalidObjectException("Illegal load factor: " + loadFactor); s.readInt(); // Read and ignore number of buckets int mappings = s.readInt(); // Read number of mappings (size) if (mappings < 0) throw new InvalidObjectException("Illegal mappings count: " + mappings); else if (mappings > 0) { // (if zero, use defaults) // Size the table using given load factor only if within // range of 0.25...4.0 float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f); float fc = (float)mappings / lf + 1.0f; int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ? DEFAULT_INITIAL_CAPACITY : (fc >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int)fc)); float ft = (float)cap * lf; threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ? (int)ft : Integer.MAX_VALUE); @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] tab = (Node<K,V>[])new Node[cap]; table = tab; // Read the keys and values, and put the mappings in the HashMap for (int i = 0; i < mappings; i++) { @SuppressWarnings("unchecked") K key = (K) s.readObject(); @SuppressWarnings("unchecked") V value = (V) s.readObject(); putVal(hash(key), key, value, false, false); } } } /* ------------------------------------------------------------ */ // iterators abstract class HashIterator { Node<K,V> next; // next entry to return Node<K,V> current; // current entry int expectedModCount; // for fast-fail int index; // current slot HashIterator() { expectedModCount = modCount; Node<K,V>[] t = table; current = next = null; index = 0; if (t != null && size > 0) { // advance to first entry do {} while (index < t.length && (next = t[index++]) == null); } } public final boolean hasNext() { return next != null; } final Node<K,V> nextNode() { Node<K,V>[] t; Node<K,V> e = next; if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (e == null) throw new NoSuchElementException(); if ((next = (current = e).next) == null && (t = table) != null) { do {} while (index < t.length && (next = t[index++]) == null); } return e; } public final void remove() { Node<K,V> p = current; if (p == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); current = null; K key = p.key; removeNode(hash(key), key, null, false, false); expectedModCount = modCount; } } final class KeyIterator extends HashIterator implements Iterator<K> { public final K next() { return nextNode().key; } } final class ValueIterator extends HashIterator implements Iterator<V> { public final V next() { return nextNode().value; } } final class EntryIterator extends HashIterator implements Iterator<Map.Entry<K,V>> { public final Map.Entry<K,V> next() { return nextNode(); } } /* ------------------------------------------------------------ */ // spliterators static class HashMapSpliterator<K,V> { final HashMap<K,V> map; Node<K,V> current; // current node int index; // current index, modified on advance/split int fence; // one past last index int est; // size estimate int expectedModCount; // for comodification checks HashMapSpliterator(HashMap<K,V> m, int origin, int fence, int est, int expectedModCount) { this.map = m; this.index = origin; this.fence = fence; this.est = est; this.expectedModCount = expectedModCount; } final int getFence() { // initialize fence and size on first use int hi; if ((hi = fence) < 0) { HashMap<K,V> m = map; est = m.size; expectedModCount = m.modCount; Node<K,V>[] tab = m.table; hi = fence = (tab == null) ? 0 : tab.length; } return hi; } public final long estimateSize() { getFence(); // force init return (long) est; } } static final class KeySpliterator<K,V> extends HashMapSpliterator<K,V> implements Spliterator<K> { KeySpliterator(HashMap<K,V> m, int origin, int fence, int est, int expectedModCount) { super(m, origin, fence, est, expectedModCount); } public KeySpliterator<K,V> trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; return (lo >= mid || current != null) ? null : new KeySpliterator<>(map, lo, index = mid, est >>>= 1, expectedModCount); } public void forEachRemaining(Consumer<? super K> action) { int i, hi, mc; if (action == null) throw new NullPointerException(); HashMap<K,V> m = map; Node<K,V>[] tab = m.table; if ((hi = fence) < 0) { mc = expectedModCount = m.modCount; hi = fence = (tab == null) ? 0 : tab.length; } else mc = expectedModCount; if (tab != null && tab.length >= hi && (i = index) >= 0 && (i < (index = hi) || current != null)) { Node<K,V> p = current; current = null; do { if (p == null) p = tab[i++]; else { action.accept(p.key); p = p.next; } } while (p != null || i < hi); if (m.modCount != mc) throw new ConcurrentModificationException(); } } public boolean tryAdvance(Consumer<? super K> action) { int hi; if (action == null) throw new NullPointerException(); Node<K,V>[] tab = map.table; if (tab != null && tab.length >= (hi = getFence()) && index >= 0) { while (current != null || index < hi) { if (current == null) current = tab[index++]; else { K k = current.key; current = current.next; action.accept(k); if (map.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } } } return false; } public int characteristics() { return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) | Spliterator.DISTINCT; } } static final class ValueSpliterator<K,V> extends HashMapSpliterator<K,V> implements Spliterator<V> { ValueSpliterator(HashMap<K,V> m, int origin, int fence, int est, int expectedModCount) { super(m, origin, fence, est, expectedModCount); } public ValueSpliterator<K,V> trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; return (lo >= mid || current != null) ? null : new ValueSpliterator<>(map, lo, index = mid, est >>>= 1, expectedModCount); } public void forEachRemaining(Consumer<? super V> action) { int i, hi, mc; if (action == null) throw new NullPointerException(); HashMap<K,V> m = map; Node<K,V>[] tab = m.table; if ((hi = fence) < 0) { mc = expectedModCount = m.modCount; hi = fence = (tab == null) ? 0 : tab.length; } else mc = expectedModCount; if (tab != null && tab.length >= hi && (i = index) >= 0 && (i < (index = hi) || current != null)) { Node<K,V> p = current; current = null; do { if (p == null) p = tab[i++]; else { action.accept(p.value); p = p.next; } } while (p != null || i < hi); if (m.modCount != mc) throw new ConcurrentModificationException(); } } public boolean tryAdvance(Consumer<? super V> action) { int hi; if (action == null) throw new NullPointerException(); Node<K,V>[] tab = map.table; if (tab != null && tab.length >= (hi = getFence()) && index >= 0) { while (current != null || index < hi) { if (current == null) current = tab[index++]; else { V v = current.value; current = current.next; action.accept(v); if (map.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } } } return false; } public int characteristics() { return (fence < 0 || est == map.size ? Spliterator.SIZED : 0); } } static final class EntrySpliterator<K,V> extends HashMapSpliterator<K,V> implements Spliterator<Map.Entry<K,V>> { EntrySpliterator(HashMap<K,V> m, int origin, int fence, int est, int expectedModCount) { super(m, origin, fence, est, expectedModCount); } public EntrySpliterator<K,V> trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; return (lo >= mid || current != null) ? null : new EntrySpliterator<>(map, lo, index = mid, est >>>= 1, expectedModCount); } public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) { int i, hi, mc; if (action == null) throw new NullPointerException(); HashMap<K,V> m = map; Node<K,V>[] tab = m.table; if ((hi = fence) < 0) { mc = expectedModCount = m.modCount; hi = fence = (tab == null) ? 0 : tab.length; } else mc = expectedModCount; if (tab != null && tab.length >= hi && (i = index) >= 0 && (i < (index = hi) || current != null)) { Node<K,V> p = current; current = null; do { if (p == null) p = tab[i++]; else { action.accept(p); p = p.next; } } while (p != null || i < hi); if (m.modCount != mc) throw new ConcurrentModificationException(); } } public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) { int hi; if (action == null) throw new NullPointerException(); Node<K,V>[] tab = map.table; if (tab != null && tab.length >= (hi = getFence()) && index >= 0) { while (current != null || index < hi) { if (current == null) current = tab[index++]; else { Node<K,V> e = current; current = current.next; action.accept(e); if (map.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } } } return false; } public int characteristics() { return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) | Spliterator.DISTINCT; } } /* ------------------------------------------------------------ */ // LinkedHashMap support /* * The following package-protected methods are designed to be * overridden by LinkedHashMap, but not by any other subclass. * Nearly all other internal methods are also package-protected * but are declared final, so can be used by LinkedHashMap, view * classes, and HashSet. */ // Create a regular (non-tree) node Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) { return new Node<>(hash, key, value, next); } // For conversion from TreeNodes to plain nodes Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) { return new Node<>(p.hash, p.key, p.value, next); } // Create a tree bin node TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) { return new TreeNode<>(hash, key, value, next); } // For treeifyBin TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) { return new TreeNode<>(p.hash, p.key, p.value, next); } /** * Reset to initial default state. Called by clone and readObject. */ void reinitialize() { table = null; entrySet = null; keySet = null; values = null; modCount = 0; threshold = 0; size = 0; } // Callbacks to allow LinkedHashMap post-actions void afterNodeAccess(Node<K,V> p) { } void afterNodeInsertion(boolean evict) { } void afterNodeRemoval(Node<K,V> p) { } // Called only from writeObject, to ensure compatible ordering. void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException { Node<K,V>[] tab; if (size > 0 && (tab = table) != null) { for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) { s.writeObject(e.key); s.writeObject(e.value); } } } } /* ------------------------------------------------------------ */ // Tree bins /** * JDK1.8新增,用来支持桶的红黑树结构实现 * 性质1. 节点是红色或黑色。 * 性质2. 根是黑色。 * 性质3. 所有叶子都是黑色(叶子是NIL节点)。 * 性质4. 每个红色节点必须有两个黑色的子节点。(从每个叶子到根的所有路径上不能有两个连续的红色节点。) * 性质5. 从任一节点到其每个叶子的所有简单路径都包含相同数目的黑色节点。 */ static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> { TreeNode<K,V> parent; //节点的父亲 TreeNode<K,V> left; //节点的左孩子 TreeNode<K,V> right; //节点的右孩子 TreeNode<K,V> prev; //节点的前一个节点 boolean red; //true表示红节点,false表示黑节点 TreeNode(int hash, K key, V val, Node<K,V> next) { super(hash, key, val, next); } /** * 获取红黑树的根 */ final TreeNode<K,V> root() { for (TreeNode<K,V> r = this, p;;) { if ((p = r.parent) == null) return r; r = p; } } /** *确保root是桶中的第一个元素 ,将root移到中中的第一个 */ 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); } } /** * 查找hash为h,key为k的节点 */ 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; } /** * 获取树节点,通过根节点查找 */ final TreeNode<K,V> getTreeNode(int h, Object k) { return ((parent != null) ? root() : this).find(h, k, null); } /** * 比较2个对象的大小 */ 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; } /** *将链表转为二叉树 * @return root of tree */ 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); } /** * 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; } /** * 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; } } } /** * 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 || 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); } /** * Splits nodes in a tree bin into lower and upper tree bins, * or untreeifies if now too small. Called only from resize; * see above discussion about split bits and indices. * * @param map the map * @param tab the table for recording bin heads * @param index the index of the table being split * @param bit the bit of hash to split on */ final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) { TreeNode<K,V> b = this; // Relink into lo and hi lists, preserving order TreeNode<K,V> loHead = null, loTail = null; TreeNode<K,V> hiHead = null, hiTail = null; int lc = 0, hc = 0; for (TreeNode<K,V> e = b, next; e != null; e = next) { next = (TreeNode<K,V>)e.next; e.next = null; if ((e.hash & bit) == 0) { if ((e.prev = loTail) == null) loHead = e; else loTail.next = e; loTail = e; ++lc; } else { if ((e.prev = hiTail) == null) hiHead = e; else hiTail.next = e; hiTail = e; ++hc; } } if (loHead != null) { if (lc <= UNTREEIFY_THRESHOLD) tab[index] = loHead.untreeify(map); else { tab[index] = loHead; if (hiHead != null) // (else is already treeified) loHead.treeify(tab); } } if (hiHead != null) { if (hc <= UNTREEIFY_THRESHOLD) tab[index + bit] = hiHead.untreeify(map); else { tab[index + bit] = hiHead; if (loHead != null) hiHead.treeify(tab); } } } /* ------------------------------------------------------------ */ // Red-black tree methods, all adapted from CLR static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root, TreeNode<K,V> p) { TreeNode<K,V> r, pp, rl; if (p != null && (r = p.right) != null) { if ((rl = p.right = r.left) != null) rl.parent = p; if ((pp = r.parent = p.parent) == null) (root = r).red = false; else if (pp.left == p) pp.left = r; else pp.right = r; r.left = p; p.parent = r; } return root; } static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root, TreeNode<K,V> p) { TreeNode<K,V> l, pp, lr; if (p != null && (l = p.left) != null) { if ((lr = p.left = l.right) != null) lr.parent = p; if ((pp = l.parent = p.parent) == null) (root = l).red = false; else if (pp.right == p) pp.right = l; else pp.left = l; l.right = p; p.parent = l; } return root; } static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root, TreeNode<K,V> x) { x.red = true; for (TreeNode<K,V> xp, xpp, xppl, xppr;;) { if ((xp = x.parent) == null) { x.red = false; return x; } else if (!xp.red || (xpp = xp.parent) == null) return root; if (xp == (xppl = xpp.left)) { if ((xppr = xpp.right) != null && xppr.red) { xppr.red = false; xp.red = false; xpp.red = true; x = xpp; } else { if (x == xp.right) { root = rotateLeft(root, x = xp); xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null) { xp.red = false; if (xpp != null) { xpp.red = true; root = rotateRight(root, xpp); } } } } else { if (xppl != null && xppl.red) { xppl.red = false; xp.red = false; xpp.red = true; x = xpp; } else { if (x == xp.left) { root = rotateRight(root, x = xp); xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null) { xp.red = false; if (xpp != null) { xpp.red = true; root = rotateLeft(root, xpp); } } } } } } static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root, TreeNode<K,V> x) { for (TreeNode<K,V> xp, xpl, xpr;;) { if (x == null || x == root) return root; else if ((xp = x.parent) == null) { x.red = false; return x; } else if (x.red) { x.red = false; return root; } else if ((xpl = xp.left) == x) { if ((xpr = xp.right) != null && xpr.red) { xpr.red = false; xp.red = true; root = rotateLeft(root, xp); xpr = (xp = x.parent) == null ? null : xp.right; } if (xpr == null) x = xp; else { TreeNode<K,V> sl = xpr.left, sr = xpr.right; if ((sr == null || !sr.red) && (sl == null || !sl.red)) { xpr.red = true; x = xp; } else { if (sr == null || !sr.red) { if (sl != null) sl.red = false; xpr.red = true; root = rotateRight(root, xpr); xpr = (xp = x.parent) == null ? null : xp.right; } if (xpr != null) { xpr.red = (xp == null) ? false : xp.red; if ((sr = xpr.right) != null) sr.red = false; } if (xp != null) { xp.red = false; root = rotateLeft(root, xp); } x = root; } } } else { // symmetric if (xpl != null && xpl.red) { xpl.red = false; xp.red = true; root = rotateRight(root, xp); xpl = (xp = x.parent) == null ? null : xp.left; } if (xpl == null) x = xp; else { TreeNode<K,V> sl = xpl.left, sr = xpl.right; if ((sl == null || !sl.red) && (sr == null || !sr.red)) { xpl.red = true; x = xp; } else { if (sl == null || !sl.red) { if (sr != null) sr.red = false; xpl.red = true; root = rotateLeft(root, xpl); xpl = (xp = x.parent) == null ? null : xp.left; } if (xpl != null) { xpl.red = (xp == null) ? false : xp.red; if ((sl = xpl.left) != null) sl.red = false; } if (xp != null) { xp.red = false; root = rotateRight(root, xp); } x = root; } } } } } /** * Recursive invariant check */ static <K,V> boolean checkInvariants(TreeNode<K,V> t) { TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right, tb = t.prev, tn = (TreeNode<K,V>)t.next; if (tb != null && tb.next != t) return false; if (tn != null && tn.prev != t) return false; if (tp != null && t != tp.left && t != tp.right) return false; if (tl != null && (tl.parent != t || tl.hash > t.hash)) return false; if (tr != null && (tr.parent != t || tr.hash < t.hash)) return false; if (t.red && tl != null && tl.red && tr != null && tr.red) return false; if (tl != null && !checkInvariants(tl)) return false; if (tr != null && !checkInvariants(tr)) return false; return true; } } }
---------------------
作者:轩辕花狐貂
来源:CSDN
原文:https://blog.csdn.net/qq_35558797/article/details/79895095
版权声明:本文为博主原创文章,转载请附上博文链接!
以上是关于HashMap key使用注意事项 key“存在“却获取不到原因的主要内容,如果未能解决你的问题,请参考以下文章