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 |
static class <K,V> implements Map.Entry<K,V> { |
1 |
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> { |
TreeNode 是新增的红黑树节点,有父亲,左右孩子,前一个元素的节点,还有颜色值
因为新型红黑树节点的出现,HashMap 中多了三个关键属性:
1 |
/** |
- TREEIFY_THRESHOLD : 链表节点转红黑树节点的阈值,当节点数量大于8个时,链表节点转化为红黑树节点
- UNTREEIFY_THRESHOLD : 红黑树节点还原链表节点的阈值,当扩容时,元素数量小于这个值,红黑树节点转化为链表节点
- MIN_TREEIFY_CAPACITY : 哈希表最小树形化容量