定义
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
可以看到HashMap是继承 AbstractMap实现了Map,Cloneable,Servializable接口的一个类。
Map
Map接口定义了我们日常工作中用map处理的常用函数
int size();
int size();
...
interface Entry<K,V> { ... } //定义了存储数据的接口
default V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction) { ... }
default V computeIfPresent(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) { ... }
default V compute(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction)
default V merge(K key, V value,
BiFunction<? super V, ? super V, ? extends V> remappingFunction)
里边比较不常见的方法是几个compute
方法,这是java8加入的函数式接口编程新特性,详情可以参见 http://colobu.com/2014/10/28/secrets-of-java-8-functional-interface/.这里举个例子来展示下:
public class Test {
public static void main(String [] args) {
Map<Integer, Integer> map = new HashMap<>();
map.computeIfAbsent(1, Test::mul); // 将key * 2然后放入map {1=2}
map.computeIfPresent(1, Test::add); // 将key + map.get(key)然后放入map {1=3}
map.merge(1, 3, Test::add); // 将map.get(key) + 3 放入map {1=6}
System.out.println(map);
}
public static int mul(int a) {
return a * 2;
}
public static int add(int a, int b) {
return a + b;
}
}
AbstractMap
AbstractMap只是提供一个基础的实现,实现了Map.Entry。
public static class SimpleEntry<K,V>
implements Entry<K,V>, java.io.Serializable { ... }
public static class SimpleImmutableEntry<K,V>
implements Entry<K,V>, java.io.Serializable { ... }
HashMap
HashMap对Map.Entry实现如下:
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
}
我们常用的建立HashMap调用如下构造方法:
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
这个构造方法只设置了负载因子,默认值为0.75,那么HashMap初始化是在什么地方完成的呢?
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 {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
当我们第一次调用put方法的时候,会调用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 = 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;
}
resize()
方法在发现HashMap没有初始化capacity
和threshold
的时候,会将他们的值设置为初始值(DEFAULT_INITIAL_CAPACITY,DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY)
,所以初始capacity
的值为16,threshold
值为12。默认值的定义如下:
/**
* 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;
/**
* 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;
HashMap中的hash函数为(capacity-1)&hash(key)
,持续放入新的值,当存入的节点数超过threshold
的时候,会再次触发resize()
方法,此时会将capacity
和threshold
右移一位,将老的节点数组中的节点移动新的节点数组中,然后将老的数组元素显式设置为null。由于容量向右移动一位,那么hash的时候原来同一个桶中的数据会根据最高位不同被分到两个桶中,然后循环将原来的值分成两个链表,将表头分别赋值给新的桶就完成了数据的迁移。
如果一个桶中的节点数超过 TREEIFY_THRESHOLD (=8)
时,会触发treeifyBin()
,treeifyBin()
会将capacity
大于MIN_TREEIFY_CAPACITY (=64)
的HashMap中hash到同一个桶中的节点用红黑树来存储(Node -> TreeNode)。