背景
如果大家对HashMap有一定了解的话,那么首先知道,红黑树结构是JDK8中对HashMap优化后新增的数据结构。JDK7中HashMap的数据结构是数组+链表构成的哈希表,JDK8中的HashMap的数据结构是数组+链表+红黑树。
网上有很多关于HashMap底层原理的文章,但是其中对HashMap在扩容时红黑树的结构描述的不清楚或者不准确,本文通过源码对红黑树问题进行剖析。
这里我们使用的jdk版本是1.8.0_162
基础知识
要分析源码,首先我们需要有一些基础知识。
equals()方法和hashCode()方法
关于这两个方法,只需要记住重写equals()方法后,一定要重写hashCode方法,原因是JDK中有很多API和这两个方法有关系,正如JDK的建议一样,equals方法返回true的两个对象,hashCode应该是相同的,除此之外没有别的要求,也就是说equals方法返回为false的两个对象,hashCode可以相同也可以不相同。
哈希表数据结构
首先要了解的是哈希表的数据结构。前文提过,HashMap的底层就是通过数组+链表+红黑树的方式实现的哈希表结构。数组结构可以在O(1)的时间复杂度定位元素在数组中的位置,而位置是通过key的哈希值和数组长度取模计算出来的,而哈希值是可能相同的,也就是哈希冲突,当然,哈希值不同的时候,通过取模计算也可能产生哈希冲突,所以相同索引下的键的哈希值是可能不相同的或者说,绝大多数是不相同的。当哈希冲突时,就用到链表或者红黑树来解决,当多个元素产生哈希冲突时,这些元素都映射到数组的同一个位置,通过链表或者红黑树结构把这些元素连接起来。
这里解释一下为什么equals方法返回true的两个对象,hashCode值也应该一样?
我们假设有一个对象,通过计算hashCode正常添加到HashMap中,这时,又有一个对象,它和刚才的对象是“相同”的,也就是equals方法返回true,正常情况下,通过这个“相同”的对象,我们应该能获取之前放入的值,但是,如果这两个“相同”的对象hashCode不相同,那么当get(Object o)时,“相同”的对象被映射到了不同的数组位置上,导致获取结果为null。
源码剖析
首先需要知道HashMap中的涉及到的几个变量及内部数据结构,如下
/**
* The load factor used when none specified in constructor.
* 扩容比例
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
* 链表转换为红黑树的阈值,该阈值指定了元素最少达到8个才有可能转换为红黑树,不是一定
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
* 用来控制缩容时从红黑树转换为链表的阈值
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
* 转换为红黑树时,数组的最小容量
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
* 这是JDK8中,用来封装哈希表中链表元素的对象,添加到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节点
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;
}
}
/**
* Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
* extends Node) so can be used as extension of either regular or
* linked node.
* 红黑树数据结构,当产生哈希冲突,链表转换为红黑树时,元素节点被封装成该结构
*/
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // 父节点,红黑树中判断父子关系
TreeNode