/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
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;
}
......
我们跟进看看 Entry 是什么?
/**
* A map entry (key-value pair).
*/
interface Entry<K,V> {
...... // 省略方法定义
}
这一个个的 Node 是如何排列的呢?
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;
显而易见, HashMap 的键值对一通过一个个的 Entry 对来保存的, 实现类 Node 是一个链表节点, 底层排列方式为数组, 数组中的每一个元素都是一个链表的头结点.
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
我么知道 HashMap 是基于散列函数的,最坏的散列情况为线性的链表, 因此我们可以知道 如下这几点会极大的影响 HashMap 的性能:
在JDK 1.7 中, HashMap 是用线性链表来维持冲突的, 而 jdk 1.8 中使用了二叉查找树中的红黑树, 解决了当冲突过多, 线性检索链表效率过低的情况.
/**
* 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; // red-black tree links
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);
}
更多详细介绍: Java8 HashMap 深入理解
扩容过程源码:
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length; // 第一次添加值是 oldTab 为 null, 因此会跳转至注释 1 处, 如果不是第一次添加值而导致的扩容, 会进入后面的循环.
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold // ---------------- 2
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY; // -------------- 1
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) { // 如果 oldTab 不为 null, 说明不是第一次添加值.
for (int j = 0; j < oldCap; ++j) { // 大致的过程为循环取出 oldTab 中的每一个节点, 进行再 hash 复制到新的 tab 中的筒位中去, 由于 jdk 8 中添加了 红黑树的节点, 因此还要特殊处理红黑树.
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
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 {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
从上面源码 注释 2 处中我们可以看出, HashMap 每次扩容都会将原始容量乘以2, 即 HashMap 的容量永远都为 2 的整数次幂.
也许会有人好奇, 如果我们在构造函数中传入的初始容量不是 2 的整数次幂呢, 比如 9, 从源码中得出结果:
/**
* Constructs an empty HashMap with the specified initial
* capacity and load factor.
*
* @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) {
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); // ------- 1
}
/**
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
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;
}
进行了一系列的移位操作, 最终总是会把我们的值转换成一个比我们输入的值大的且是最近的 2 的整数次幂的值, 不信你去打断点, 或者反射拿出来调调 (嘿嘿).
至于何时扩容, 从 put 方法中找到线索:
/**
* Implements Map.put and related metho
*
*/
final V putVal(int hash, K key, V value
boolean evict) {
....... 省略put的操作逻辑.
++modCount;
if (++size > threshold) // 重点在这一行.
resize();
afterNodeInsertion(evict);
return null;
}
在每次 put 完后, 会判断 size(元素的个数) 是否大于 threshold(负载数, 等于负载因子*筒位数量), 如果大于则进行再 hash 扩容.
最后我们可以想到, 如果我们事先就能大概估计出 HashMap 中要存储多少个元素, 传入其容量, 就可以避免自动扩容而导致的再 hash 机制, 这也是提高 HashMap 效率的一种手段.