JDK 1.8 HashMap 数据结构优化

JDK 1.7 中的 HashMap 数据结构是 数组 + 链表:

JDK 1.8 中的 HashMap 数据结构是 数组 大专栏  JDK 1.8 HashMap 数据结构优化 + 链表或红黑树

在 JDK 1.7 中之所以存在链表结构是因为当哈希碰撞时,不同的元素需要存放在相同的数组位置上,故数组同一个位置需要可以保存不同的元素,JDK 1.7 中选择的是链表,当哈希碰撞剧烈,导致链表较长时,影响了 HashMap 的查找性能。

故 JDK 1.8 中 HashMap 中 Entry 是一个接口,存在两种实现类:

1
2
3
4
5
6
7
8
9
10
11
12
13
static class <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;
}
}
1
2
3
4
5
6
7
8
9
10
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; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
}

TreeNode 是新增的红黑树节点,有父亲,左右孩子,前一个元素的节点,还有颜色值

因为新型红黑树节点的出现,HashMap 中多了三个关键属性:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 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.
*/
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;
  • TREEIFY_THRESHOLD : 链表节点转红黑树节点的阈值,当节点数量大于8个时,链表节点转化为红黑树节点
  • UNTREEIFY_THRESHOLD : 红黑树节点还原链表节点的阈值,当扩容时,元素数量小于这个值,红黑树节点转化为链表节点
  • MIN_TREEIFY_CAPACITY : 哈希表最小树形化容量

猜你喜欢

转载自www.cnblogs.com/liuzhongrong/p/12434869.html