HashMap底层原理
HashMap简介
1. HashMap是用于存储Key-Value键值对的集合;
2. HashMap根据键的hashCode值存储数据,大多数情况下可以直接定位到它的值,So具有很快的访问速度,但遍历顺序不确定;
3. HashMap中键key为null的记录至多只允许一条,值value为null的记录可以有多条;
4. HashMap非线程安全,即任一时刻允许多个线程同时写HashMap,可能会导致数据的不一致。
从整体结构上看HashMap是由数组+链表+红黑树(JDK1.8后增加了红黑树部分)实现的。
数组:
HashMap是一个用于存储Key-Value键值对的集合,每一个键值对也叫做一个Entry;这些Entry分散的存储在一个数组当中,该数组就是HashMap的主干。
链表:
因为数组Table的长度是有限的,使用hash函数计算时可能会出现index冲突的情况,所以我们需要链表来解决冲突;数组Table的每一个元素不单纯只是一个Entry对象,它还是一个链表的头节点,每一个Entry对象通过Next指针指向下一个Entry节点;当新来的Entry映射到冲突数组位置时,只需要插入对应的链表位置即可。
index冲突例子如下:
比如调用 hashMap.put("China", 0) ,插入一个Key为“China"的元素;这时候我们需要利用一个哈希函数来确定Entry的具体插入位置(index):通过index = Hash("China"),假定最后计算出的index是2,那么Entry的插入结果如下:
图5. index冲突-1

但是,因为HashMap的长度是有限的,当插入的Entry越来越多时,再完美的Hash函数也难免会出现index冲突的情况。比如下面这样:
图6. index冲突-2

经过hash函数计算发现即将插入的Entry的index值也为2,这样就会与之前插入的Key为“China”的Entry起冲突;这时就可以用链表来解决冲突,当新来的Entry映射到冲突的数组位置时,只需要插入到对应的链表即可;此外,新来的Entry节点插入链表时使用的是“头插法”,即会插在链表的头部,因为HashMap的发明者认为后插入的Entry被查找的概率更大。
图7. index冲突-3

红黑树:
当链表长度超过阈值(8)时,会将链表转换为红黑树,使HashMap的性能得到进一步提升。
HashMap红黑树

HashMap底层存储结构源码:
Node<K,V>类用来实现数组及链表的数据结构:
1 /** 数组及链表的数据结构
2 * Basic hash bin node, used for most entries. (See below for
3 * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
4 */
5 static class Node<K,V> implements Map.Entry<K,V> {
6 final int hash; //保存节点的hash值
7 final K key; //保存节点的key值
8 V value; //保存节点的value值
9 //next是指向链表结构下当前节点的next节点,红黑树TreeNode节点中也用到next
10 Node<K,V> next;
11
12 Node(int hash, K key, V value, Node<K,V> next) {
13 this.hash = hash;
14 this.key = key;
15 this.value = value;
16 this.next = next;
17 }
18
19 public final K getKey() { return key; }
20 public final V getValue() { return value; }
21 public final String toString() { return key + "=" + value; }
22
23 public final int hashCode() {
24 return Objects.hashCode(key) ^ Objects.hashCode(value);
25 }
26
27 public final V setValue(V newValue) {
28 V oldValue = value;
29 value = newValue;
30 return oldValue;
31 }
32
33 public final boolean equals(Object o) {
34 if (o == this)
35 return true;
36 if (o instanceof Map.Entry) {
37 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
38 if (Objects.equals(key, e.getKey()) &&
39 Objects.equals(value, e.getValue()))
40 return true;
41 }
42 return false;
43 }
44 }
TreeNode<K,V>用来实现红黑树相关的存储结构:
1 /** 继承LinkedHashMap.Entry<K,V>,红黑树相关存储结构
2 * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
3 * extends Node) so can be used as extension of either regular or
4 * linked node.
5 */
6 static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
7 TreeNode<K,V> parent; //存储当前节点的父节点
8 TreeNode<K,V> left; //存储当前节点的左孩子
9 TreeNode<K,V> right; //存储当前节点的右孩子
10 TreeNode<K,V> prev; //存储当前节点的前一个节点
11 boolean red; //存储当前节点的颜色(红、黑)
12 TreeNode(int hash, K key, V val, Node<K,V> next) {
13 super(hash, key, val, next);
14 }
15
16 public class LinkedHashMap<K,V>
17 extends HashMap<K,V>
18 implements Map<K,V>
19 {
20
21 /**
22 * HashMap.Node subclass for normal LinkedHashMap entries.
23 */
24 static class Entry<K,V> extends HashMap.Node<K,V> {
25 Entry<K,V> before, after;
26 Entry(int hash, K key, V value, Node<K,V> next) {
27 super(hash, key, value, next);
28 }
29 }
三、HashMap各常量及成员变量的作用
HashMap相关常量:
1 /** 创建HashMap时未指定初始容量情况下的默认容量 2 * The default initial capacity - MUST be a power of two. 3 */ 4 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 1 << 4 = 16 5 6 /** HashMap的最大容量 7 * The maximum capacity, used if a higher value is implicitly specified 8 * by either of the constructors with arguments. 9 * MUST be a power of two <= 1<<30. 10 */ 11 static final int MAXIMUM_CAPACITY = 1 << 30; // 1 << 30 = 1073741824 12 13 /** HashMap默认的装载因子,当HashMap中元素数量超过 容量*装载因子 时,则进行resize()扩容操作 14 * The load factor used when none specified in constructor. 15 */ 16 static final float DEFAULT_LOAD_FACTOR = 0.75f; 17 18 /** 用来确定何时解决hash冲突的,链表转为红黑树 19 * The bin count threshold for using a tree rather than list for a 20 * bin. Bins are converted to trees when adding an element to a 21 * bin with at least this many nodes. The value must be greater 22 * than 2 and should be at least 8 to mesh with assumptions in 23 * tree removal about conversion back to plain bins upon 24 * shrinkage. 25 */ 26 static final int TREEIFY_THRESHOLD = 8; 27 28 /** 用来确定何时解决hash冲突的,红黑树转变为链表 29 * The bin count threshold for untreeifying a (split) bin during a 30 * resize operation. Should be less than TREEIFY_THRESHOLD, and at 31 * most 6 to mesh with shrinkage detection under removal. 32 */ 33 static final int UNTREEIFY_THRESHOLD = 6; 34 35 /** 当想要将解决hash冲突的链表转变为红黑树时,需要判断下此时数组的容量,若是由于数组容量太小(小于MIN_TREEIFY_CAPACITY)而导致hash冲突,则不进行链表转为红黑树的操作,而是利用resize()函数对HashMap扩容 36 * The smallest table capacity for which bins may be treeified. 37 * (Otherwise the table is resized if too many nodes in a bin.) 38 * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts 39 * between resizing and treeification thresholds. 40 */ 41 static final int MIN_TREEIFY_CAPACITY = 64;
HashMap相关成员变量:
1 /* ---------------- Fields -------------- */ 2 3 /** 保存Node<K,V>节点的数组 4 * The table, initialized on first use, and resized as 5 * necessary. When allocated, length is always a power of two. 6 * (We also tolerate length zero in some operations to allow 7 * bootstrapping mechanics that are currently not needed.) 8 */ 9 transient Node<K,V>[] table; 10 11 /** 由HashMap中Node<K,V>节点构成的set 12 * Holds cached entrySet(). Note that AbstractMap fields are used 13 * for keySet() and values(). 14 */ 15 transient Set<Map.Entry<K,V>> entrySet; 16 17 /** 记录HashMap当前存储的元素的数量 18 * The number of key-value mappings contained in this map. 19 */ 20 transient int size; 21 22 /** 记录HashMap发生结构性变化的次数(value值的覆盖不属于结构性变化) 23 * The number of times this HashMap has been structurally modified 24 * Structural modifications are those that change the number of mappings in 25 * the HashMap or otherwise modify its internal structure (e.g., 26 * rehash). This field is used to make iterators on Collection-views of 27 * the HashMap fail-fast. (See ConcurrentModificationException). 28 */ 29 transient int modCount; 30 31 /** threshold的值应等于table.length*loadFactor,size超过这个值时会进行resize()扩容 32 * The next size value at which to resize (capacity * load factor). 33 * 34 * @serial 35 */ 36 // (The javadoc description is true upon serialization. 37 // Additionally, if the table array has not been allocated, this 38 // field holds the initial array capacity, or zero signifying 39 // DEFAULT_INITIAL_CAPACITY.) 40 int threshold; 41 42 /** 记录HashMap的装载因子 43 * The load factor for the hash table. 44 * 45 * @serial 46 */ 47 final float loadFactor; 48 49 /* ---------------- Public operations -------------- */
四、HashMap的四种构造方法
HashMap提供了四个构造方法,四个构造方法中方法1、2、3都没有进行数组的初始化操作,即使调用了构造方法此时存放HaspMap的数组中元素的table表长度依旧为0 ;在第四个构造方法中调用了putMapEntries()方法完成了table的初始化操作,并将m中的元素添加到HashMap中。
1 /* ---------------- Public operations -------------- */
2
3 /** 构造方法1,指定初始容量及装载因子
4 * Constructs an empty <tt>HashMap</tt> with the specified initial
5 * capacity and load factor.
6 *
7 * @param initialCapacity the initial capacity
8 * @param loadFactor the load factor
9 * @throws IllegalArgumentException if the initial capacity is negative
10 * or the load factor is nonpositive
11 */
12 public HashMap(int initialCapacity, float loadFactor) {
13 if (initialCapacity < 0)
14 throw new IllegalArgumentException("Illegal initial capacity: " +
15 initialCapacity);
16 if (initialCapacity > MAXIMUM_CAPACITY)
17 initialCapacity = MAXIMUM_CAPACITY;
18 if (loadFactor <= 0 || Float.isNaN(loadFactor))
19 throw new IllegalArgumentException("Illegal load factor: " +
20 loadFactor);
21 this.loadFactor = loadFactor;
22 //tableSize(initialCapacity)方法返回的值最接近initialCapacity的2的幂,若设定初始容量为9,则HashMap的实际容量为16
23 //另外,通过HashMap(int initialCapacity, float loadFactor)该方法创建的HashMap初始容量的值存在threshold中
24 this.threshold = tableSizeFor(initialCapacity);
25 }
26
27
28 /** tableSizeFor(initialCapacity)方法返回的值是最接近initialCapacity的2的幂次方
29 * Returns a power of two size for the given target capacity.
30 */
31 static final int tableSizeFor(int cap) {
32 int n = cap - 1;
33 n |= n >>> 1;
34 n |= n >>> 2;
35 n |= n >>> 4;
36 n |= n >>> 8;
37 n |= n >>> 16;
38 return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
39 }
40
41 /** 构造方法2,仅指定初始容量,装载因子的值采用默认的0.75
42 * Constructs an empty <tt>HashMap</tt> with the specified initial
43 * capacity and the default load factor (0.75).
44 *
45 * @param initialCapacity the initial capacity.
46 * @throws IllegalArgumentException if the initial capacity is negative.
47 */
48 public HashMap(int initialCapacity) {
49 this(initialCapacity, DEFAULT_LOAD_FACTOR);
50 }
51
52 /** 构造方法3,所有参数均采用默认值
53 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
54 * (16) and the default load factor (0.75).
55 */
56 public HashMap() {
57 this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
58 }
59
60 /** 构造方法4,指定集合转为HashMap
61 * Constructs a new <tt>HashMap</tt> with the same mappings as the
62 * specified <tt>Map</tt>. The <tt>HashMap</tt> is created with
63 * default load factor (0.75) and an initial capacity sufficient to
64 * hold the mappings in the specified <tt>Map</tt>.
65 *
66 * @param m the map whose mappings are to be placed in this map
67 * @throws NullPointerException if the specified map is null
68 */
69 public HashMap(Map<? extends K, ? extends V> m) {
70 this.loadFactor = DEFAULT_LOAD_FACTOR;
71 putMapEntries(m, false);
72 }
73
74 /** 把Map<? extends K, ? extends V> m中的元素插入HashMap
75 * Implements Map.putAll and Map constructor
76 *
77 * @param m the map
78 * @param evict false when initially constructing this map, else
79 * true (relayed to method afterNodeInsertion).
80 */
81 final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
82 int s = m.size();
83 if (s > 0) {
84 //在创建HashMap时调用putMapEntries()函数,则table一定为空
85 if (table == null) { // pre-size
86 //根据待插入map的size计算出要创建的HashMap的容量
87 float ft = ((float)s / loadFactor) + 1.0F;
88 int t = ((ft < (float)MAXIMUM_CAPACITY) ?
89 (int)ft : MAXIMUM_CAPACITY);
90 //把要创建的HashMap的容量存在threshold中
91 if (t > threshold)
92 threshold = tableSizeFor(t);
93 }
94 //如果待插入map的size大于threshold,则进行resize()
95 else if (s > threshold)
96 resize();
97 for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
98 K key = e.getKey();
99 V value = e.getValue();
100 //最终实际上同样也是调用了putVal()函数进行元素的插入
101 putVal(hash(key), key, value, false, evict);
102 }
103 }
104 }
HashMap的put方法
假如调用hashMap.put("apple",0)方法,将会在HashMap的table数组中插入一个Key为“apple”的元素;这时需要通过hash()函数来确定该Entry的具体插入位置,而hash()方法内部会调用hashCode()函数得到“apple”的hashCode;然后putVal()方法经过一定计算得到最终的插入位置index,最后将这个Entry插入到table的index位置。
put函数:
1 /** 指定key和value,向HashMap中插入节点
2 * Associates the specified value with the specified key in this map.
3 * If the map previously contained a mapping for the key, the old
4 * value is replaced.
5 *
6 * @param key key with which the specified value is to be associated
7 * @param value value to be associated with the specified key
8 * @return the previous value associated with <tt>key</tt>, or
9 * <tt>null</tt> if there was no mapping for <tt>key</tt>.
10 * (A <tt>null</tt> return can also indicate that the map
11 * previously associated <tt>null</tt> with <tt>key</tt>.)
12 */
13 public V put(K key, V value) {
14 //插入节点,hash值的计算调用hash(key)函数,实际调用putVal()插入节点
15 return putVal(hash(key), key, value, false, true);
16 }
17
18 /** key的hash值计算是通过hashCode()的高16位异或低16位实现的:h = key.hashCode()) ^ (h >>> 16),使用位运算替代了取模运算,在table的长度比较小的情况下,也能保证hashcode的高位参与到地址映射的计算当中,同时不会有太大的开销。
19 * Computes key.hashCode() and spreads (XORs) higher bits of hash
20 * to lower. Because the table uses power-of-two masking, sets of
21 * hashes that vary only in bits above the current mask will
22 * always collide. (Among known examples are sets of Float keys
23 * holding consecutive whole numbers in small tables.) So we
24 * apply a transform that spreads the impact of higher bits
25 * downward. There is a tradeoff between speed, utility, and
26 * quality of bit-spreading. Because many common sets of hashes
27 * are already reasonably distributed (so don't benefit from
28 * spreading), and because we use trees to handle large sets of
29 * collisions in bins, we just XOR some shifted bits in the
30 * cheapest possible way to reduce systematic lossage, as well as
31 * to incorporate impact of the highest bits that would otherwise
32 * never be used in index calculations because of table bounds.
33 */
34 static final int hash(Object key) {
35 int h;
36 return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
37 }
putVal()函数:
1 /** 实际将元素插入HashMap中的方法
2 * Implements Map.put and related methods
3 *
4 * @param hash hash for key
5 * @param key the key
6 * @param value the value to put
7 * @param onlyIfAbsent if true, don't change existing value
8 * @param evict if false, the table is in creation mode.
9 * @return previous value, or null if none
10 */
11 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
12 boolean evict) {
13 Node<K,V>[] tab; Node<K,V> p; int n, i;
14 //判断table是否已初始化,否则进行初始化table操作
15 if ((tab = table) == null || (n = tab.length) == 0)
16 n = (tab = resize()).length;
17 //根据hash值确定节点在数组中的插入的位置,即计算索引存储的位置,若该位置无元素则直接进行插入
18 if ((p = tab[i = (n - 1) & hash]) == null)
19 tab[i] = newNode(hash, key, value, null);
20 else {
21 //节点若已经存在元素,即待插入位置存在元素
22 Node<K,V> e; K k;
23 //对比已经存在的元素与待插入元素的hash值和key值,执行赋值操作
24 if (p.hash == hash &&
25 ((k = p.key) == key || (key != null && key.equals(k))))
26 e = p;
27 //判断该元素是否为红黑树节点
28 else if (p instanceof TreeNode)
29 //红黑树节点则调用putTreeVal()函数进行插入
30 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
31 else {
32 //若该元素是链表,且为链表头节点,则从此节点开始向后寻找合适的插入位置
33 for (int binCount = 0; ; ++binCount) {
34 if ((e = p.next) == null) {
35 //找到插入位置后,新建节点插入
36 p.next = newNode(hash, key, value, null);
37 //若链表上节点超过TREEIFY_THRESHOLD - 1,即链表长度为8,将链表转变为红黑树
38 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
39 treeifyBin(tab, hash);
40 break;
41 }
42 //若待插入元素在HashMap中已存在,key存在了则直接覆盖
43 if (e.hash == hash &&
44 ((k = e.key) == key || (key != null && key.equals(k))))
45 break;
46 p = e;
47 }
48 }
49 if (e != null) { // existing mapping for key
50 V oldValue = e.value;
51 if (!onlyIfAbsent || oldValue == null)
52 e.value = value;
53 afterNodeAccess(e);
54 //若存在key节点,则返回旧的key值
55 return oldValue;
56 }
57 }
58 //记录修改次数
59 ++modCount;
60 //判断是否需要扩容
61 if (++size > threshold)
62 resize();
63 //空操作
64 afterNodeInsertion(evict);
65 //若不存在key节点,则返回null
66 return null;
67 }
链表转红黑树的putTreeVal()函数:
1 /** 链表转红黑树
2 * Tree version of putVal.
3 */
4 final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
5 int h, K k, V v) {
6 Class<?> kc = null;
7 boolean searched = false;
8 TreeNode<K,V> root = (parent != null) ? root() : this;
9 //从根节点开始查找合适的插入位置
10 for (TreeNode<K,V> p = root;;) {
11 int dir, ph; K pk;
12 if ((ph = p.hash) > h)
13 //若dir<0,则查找当前节点的左孩子
14 dir = -1;
15 else if (ph < h)
16 //若dir>0,则查找当前节点的右孩子
17 dir = 1;
18 //hash值或是key值相同
19 else if ((pk = p.key) == k || (k != null && k.equals(pk)))
20 return p;
21 //1.当前节点与待插入节点key不同,hash值相同
22 //2.k是不可比较的,即k未实现comparable<K>接口,或者compareComparables(kc,k,pk)的返回值为0
23 else if ((kc == null &&
24 (kc = comparableClassFor(k)) == null) ||
25 (dir = compareComparables(kc, k, pk)) == 0) {
26 //在以当前节点为根节点的整个树上搜索是否存在待插入节点(只搜索一次)
27 if (!searched) {
28 TreeNode<K,V> q, ch;
29 searched = true;
30 if (((ch = p.left) != null &&
31 (q = ch.find(h, k, kc)) != null) ||
32 ((ch = p.right) != null &&
33 (q = ch.find(h, k, kc)) != null))
34 //若搜索发现树中存在待插入节点,则直接返回
35 return q;
36 }
37 //指定了一个k的比较方式 tieBreakOrder
38 dir = tieBreakOrder(k, pk);
39 }
40
41 TreeNode<K,V> xp = p;
42 if ((p = (dir <= 0) ? p.left : p.right) == null) {
43 //找到了待插入位置,xp为待插入位置的父节点,TreeNode节点中既存在树状关系,又存在链式关系,而且还是双端链表
44 Node<K,V> xpn = xp.next;
45 TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
46 if (dir <= 0)
47 xp.left = x;
48 else
49 xp.right = x;
50 xp.next = x;
51 x.parent = x.prev = xp;
52 if (xpn != null)
53 ((TreeNode<K,V>)xpn).prev = x;
54 //插入节点后进行二叉树平衡操作
55 moveRootToFront(tab, balanceInsertion(root, x));
56 return null;
57 }
58 }
59 }
60
61 /** 定义了一个k的比较方法
62 * Tie-breaking utility for ordering insertions when equal
63 * hashCodes and non-comparable. We don't require a total
64 * order, just a consistent insertion rule to maintain
65 * equivalence across rebalancings. Tie-breaking further than
66 * necessary simplifies testing a bit.
67 */
68 static int tieBreakOrder(Object a, Object b) {
69 int d;
70 if (a == null || b == null ||
71 (d = a.getClass().getName().
72 compareTo(b.getClass().getName())) == 0)
73 //System.identityHashCode()实际是比较对象a,b的内存地址
74 d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
75 -1 : 1);
76 return d;
77 }
HashMap的put方法执行流程图,可以总结为如下主要步骤:
1. 判断数组table是否为null,若为null则执行resize()扩容操作。
2. 根据键key的值计算hash值得到插入的数组索引i,若table[i] == nulll,则直接新建节点插入,进入步骤6;若table[i]非null,则继续执行下一步。
3. 判断table[i]的首个元素key是否和当前key相同(hashCode和equals均相同),若相同则直接覆盖value,进入步骤6,反之继续执行下一步。
4. 判断table[i]是否为treeNode,若是红黑树,则直接在树中插入键值对并进入步骤6,反之继续执行下一步。
5. 遍历table[i],判断链表长度是否大于8,若>8,则把链表转换为红黑树,在红黑树中执行插入操作;若<8,则进行链表的插入操作;遍历过程中若发现key已存在则会直接覆盖该key的value值。
6. 插入成功后,判断实际存在的键值对数量size是否超过了最大容量threshold,若超过则进行扩容。
六、HashMap的get方法
get()和getNode()函数:
1 /**
2 * Returns the value to which the specified key is mapped,
3 * or {@code null} if this map contains no mapping for the key.
4 *
5 * <p>More formally, if this map contains a mapping from a key
6 * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
7 * key.equals(k))}, then this method returns {@code v}; otherwise
8 * it returns {@code null}. (There can be at most one such mapping.)
9 *
10 * <p>A return value of {@code null} does not <i>necessarily</i>
11 * indicate that the map contains no mapping for the key; it's also
12 * possible that the map explicitly maps the key to {@code null}.
13 * The {@link #containsKey containsKey} operation may be used to
14 * distinguish these two cases.
15 *
16 * @see #put(Object, Object)
17 */
18 public V get(Object key) {
19 Node<K,V> e;
20 //实际上是根据输入节点的hash值和key值,利用getNode方法进行查找
21 return (e = getNode(hash(key), key)) == null ? null : e.value;
22 }
23
24 /**
25 * Implements Map.get and related methods
26 *
27 * @param hash hash for key
28 * @param key the key
29 * @return the node, or null if none
30 */
31 final Node<K,V> getNode(int hash, Object key) {
32 Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
33 if ((tab = table) != null && (n = tab.length) > 0 &&
34 (first = tab[(n - 1) & hash]) != null) {
35 if (first.hash == hash && // always check first node
36 ((k = first.key) == key || (key != null && key.equals(k))))
37 return first;
38 if ((e = first.next) != null) {
39 if (first instanceof TreeNode)
40 //若定位到的节点是TreeNode节点,则在树中进行查找
41 return ((TreeNode<K,V>)first).getTreeNode(hash, key);
42 do {
43 //反之,在链表中查找
44 if (e.hash == hash &&
45 ((k = e.key) == key || (key != null && key.equals(k))))
46 return e;
47 } while ((e = e.next) != null);
48 }
49 }
50 return null;
51 }
getTreeNode()和find()函数:
1 /** 从根节点开始,调用find()方法进行查找
2 * Calls find for root node.
3 */
4 final TreeNode<K,V> getTreeNode(int h, Object k) {
5 return ((parent != null) ? root() : this).find(h, k, null);
6 }
7
8 /**
9 * Finds the node starting at root p with the given hash and key.
10 * The kc argument caches comparableClassFor(key) upon first use
11 * comparing keys.
12 */
13 final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
14 TreeNode<K,V> p = this;
15 do {
16 int ph, dir; K pk;
17 TreeNode<K,V> pl = p.left, pr = p.right, q;
18 //首先进行hash值的比较,若不同则令当前节点变为它的左孩子or右孩子
19 if ((ph = p.hash) > h)
20 p = pl;
21 else if (ph < h)
22 p = pr;
23 //若hash值相同,进行key值的比较
24 else if ((pk = p.key) == k || (k != null && k.equals(pk)))
25 return p;
26 else if (pl == null)
27 p = pr;
28 else if (pr == null)
29 p = pl;
30 //执行到这里,说明了hash值是相同的,key值不同
31 //若k是可比较的并且k.compareTo(pk)的返回结果不为0,则进入下面的else if
32 else if ((kc != null ||
33 (kc = comparableClassFor(k)) != null) &&
34 (dir = compareComparables(kc, k, pk)) != 0)
35 p = (dir < 0) ? pl : pr;
36 //若k是不可比较的,或者k.compareTo(pk)返回结果为0,则在整棵树中查找,先找右子树,没找到则再到左子树找
37 else if ((q = pr.find(h, k, kc)) != null)
38 return q;
39 else
40 p = pl;
41 } while (p != null);
42 return null;
43 }

浙公网安备 33010602011771号