[Java 8 HashMap 详解系列] 文章目录
1.HashMap 的存储数据结构
2.HashMap 中 Key 的 index 是怎样计算的?
3.HashMap 的 put() 方法执行原理
4.HashMap 的 get() 方法执行原理
5.HashMap 的 remove() 方法执行原理
6.HashMap 的扩容 resize() 原理
7.HashMap 中的红黑树原理
1.HashMap 的存储数据结构
为什么使用 Node<K,V>[] 数组的数据结构来存储?
从底层数据结构来说,HashMap是通过数组+链表+红黑树来进行数据存储的,数组是为了通过通过下标直接定位到数据,链表和红黑树都是为了解决冲突而引入的,红黑树是为了解决在冲突比较严重时,链表过长而导致查询效率降低,从面通过红黑树来提升查询效率。HashMap底层基本的存储结构如下图所示:

public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
/* ---------------- Fields -------------- */
/**
* 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底层基本的结构就是一个数组table=Node<K,V>[],通过Key的hashCode定位到相应的位置(下标),然后在链表或红黑树中插入Node<K,V>节点,从而完成整个HashMap数据的存储。接下来,我们看一下承载数据的Node<K,V>的定义是怎么样的:
/**
* 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;
...
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;
}
}
分清楚几个概念:capacity、size、threshold
作为Java中最常用的K-V数据类型,HashMap的源码有很多地方值得细读。首先,需要区分清楚几个概念:capacity、size、threshold.
容量(capacity)
是指当前map最多可以存放多少个元素,
大小 ( size )
是指当前map已经存放了多少个k-v键值对。
threshold 阈值
是扩容的阈值,当size超过阈值后,便需要对map进行扩容。也就是说,一般情况下,map当中的键值对数量不会达到其容量上限。阈值一般为:capacity*loadFactor(负载因子)
一、默认情况下,new HashMap()得到的对象,其容量为16,负载因子为0.75
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
二、在初始化map时,若指定了容量大小,那么,实际的容量值为大于等于该数的第一个2的幂的值。
即:tableSizeFor方法结果: (1 => 1 ; 5=> 8 ; 8=>8 ; 9=> 16)
在下面的代码执行时:
Map m = new HashMap(5);
实际调用了:
/**
* 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;
}
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);
}
这里的tableForSize方法,位移操作,在进行按位或,实际上是将一个二进制数从最高位不为0起,将其后面所有的位数都置为1.
例如:
0010 0000 (原始数据)
0001 0000 (右移1位)
-------------(按位 或)
0011 0000
0000 1100
-------------
0011 1100
0000 0011
-------------
0011 1111
所以,tableForSize方法,实际上是将一个32位的数据,从最高位不为0起,后面全部置为1,然后再+1,结果就是最接近指定大小的数的2的幂.
值得注意的是,上面的源码中,是将tableForSize的值赋值给了threshold, 那为何说是我们初始化容量(capacity)的大小为该值呢?
因为在Map初始化时,是第一次向map添加数据才会触发的。第一次put数据时,调用:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length; //注意这一行代码
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
...
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
注意上面,putVal会判断table是否为null
if ((tab = table) == null || (n = tab.length) == 0)
如果为null,则调用resize方法:
n = (tab = resize()).length;
而resize方法中:
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
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
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr; //注意这一行代码
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
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作为了初始化的容量大小。
不过,对于初始化容量为1时,即
new HashMap(1)
.
此刻的capacity有一点不同,就是在没有调用put方法时,capacity==1 ;
再调用put之后,capacity ==2。这是因为发生了扩容:
HashMap<String,String> m = new HashMap(1);
//m.put("",""); //调用之后,capacatiy会等于2
Method method = m.getClass().getDeclaredMethod("capacity");
method.setAccessible(true);
System.out.println(method.invoke(m)); // 输出:1
其它情况下:
HashMap<String,String> m = new HashMap(3);
//m.put("",""); //调用之后,capacatiy会等于4,调用与否都是一致的
Method method = m.getClass().getDeclaredMethod("capacity");
method.setAccessible(true);
System.out.println(method.invoke(m)); // 输出:4
实际上,调用capacity方法时:
final int capacity() {
return (table != null) ? table.length :
(threshold > 0) ? threshold :
DEFAULT_INITIAL_CAPACITY;
}
如果已经初始化了 table 数组,则返回数组的大小,否则返回 threadhold.
三、扩容时的操作
/**
* 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;
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
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
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) {
for (int j = 0; j < oldCap; ++j) {
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;
}
每次触发扩容时,capacity会变为原来的两倍:
newThr = oldThr << 1; // double threshold
.
为什么 HashMap 的容量必须是2的n次方?
为什么HashMap 最大容量 MAXIMUM_CAPACITY 设置成1 << 30?
HashMap
内部由
Entry[]
数组构成,Java 的数组下标是由
int
表示的。所以对于HashMap来说其最大的容量应该是不超过int最大值的一个 2 的指数幂,而最接近
int
最大值的2个指数幂用位运算符表示就是
1 << 30
.