HashMap是数组+链表+红黑树。
上图就是一个Node数组
transient Node<K,V>[] table;
每个黑点就是个Node
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; //这个hash是key的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;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
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;
}
}
Node.hash是key的hash
1.8的HashMap增加了红黑树来增加存取效率,红黑树的节点
TreeNode
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V>
//下面是LinkedHashMap.Entry
static class Entry<K,V> extends HashMap.Node<K,V>
这样是为了红黑树与链表之间的转换。TreeNode的方法很多,就不贴出来了。
关于hash,数组容量
HashMap有四个构造器,我们以其中两个来说说其过程
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
数组大小16,阀值12
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
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);
}
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;
}
并不会初始化数组大小,反而会先设置阀值threshold,tableSizeFor会返回大于等于传入值的最小2的指数。如传入17,返回32(2^5)。那么什么时候初始化数组大小?第一次调用put时,在putVal中在这种情况下会调用resize方法,在该方法中会在阀值不为零而数组未初始化的情况下将数组大小设为阀值大小。
所以不管怎样数组大小一定是2的指数,为什么?HashMap的Hash算法本质上是三步:取key的hashCode值、高位运算、取模运算。
- key的hash计算
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
高16位异或低16位。这样保证在数组较小的情况下,hashcode的高位也能被考虑进来,减少冲突。
- key在table[]中位置计算
(n - 1) & hash
这里便是上面问题的解答,让大小是2^n,是为了对取模运算进行优化,&比%具有更高的效率,当length总是2的n次方时,h& (length-1)运算等价于对length取模,也就是h%length。
一般情况下我们考虑素数作为数组的大小,素数导致冲突的概率小于合数,例如HashTable初始就是11。为什么一般hashtable的桶数会取一个素数
之前文章中介绍过散列表,对于一个散列表来说存取效率和两方面有关:1.hash函数:计算结果分散越均匀,hash碰撞的概率就越小,存取效率就会越高; 2,扩容机制,数组太大浪费空间,太小费时间。
扩容机制resize
超过阀值进行扩容,阀值threshold = capacity * loadFactor,来看看扩容过程
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) // 有一个构造函数是接收map的,这种情况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不仅承担了扩容的功能,还有初始化数组大小的功能。
1.如果oldCap > 0,将数组大小扩大两倍,阀值同样扩大两倍
2.如果oldCap == 0 && oldThr > 0,比如调用了规定容量大小的构造函数。将容量设为阀值大小。
3.如果oldCap ==0代表初始化操作,数组大小为16,阀值为12。
3.接下来如果oldTab != null代表是扩容操作,对节点重新定位,一个节点的hash是key的hash,在确定它在数组中的位置是在putVal方法中,采用的是hash & (capacity-1),capacity能取什么值?2的指数倍,那么在重新安排新位置时先遍历数组,针对每个bin,将里面的节点按照hash & capacity分为两拨,一波hash & capacit == 0放在旧位置处,另一波放在oldCap + 旧位置 = 新位置处。
这张图显示了扩容后节点的重新安排。
扩容后数组变为原来的两倍,那么一个节点的hash & (capacity-1)的值要么等于原来,要么移动2的幂次方。
这个设计确实非常的巧妙,既省去了重新计算hash值的时间,而且同时,由于新增的1bit是0还是1可以认为是随机的,因此resize的过程,均匀的把之前的冲突的节点分散到新的bucket了
4.再来说说TreeNode的split方法,同链表处理相同,仍分为两拨,分法也一样,这里当其中一方节点数<=6,则恢复成链表;否则重新树化treeify。
2.HashMap的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 {
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;
}
putVal的逻辑很清晰,如果key存在onlyIfAbsent为false表示更新value值,至于afterNodeAccess与afterNodeInsertion与LinkedHashMap有关。其他的比如要考虑到普通节点还是树节点,普通节点插入后还要判断是否进行树化。如果数量大于阀值就得进行resize。注意threshold指的是节点总数而不是数组大小。
图里链表长度是否大于8判断这块,这里源码的逻辑是如果key原先链表有则替换value值,否则将键值对插入链表,之后如果长度大于8,将链表树化。
树化调用的是treeifyBin
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
当数组大小 < 64时,执行扩容操作。即当某个bin的节点个数大于8,但数组大小 < 64,进行扩容而不是树化。
关于HashMap的死循环
1.7的HashMap在多线程下resize是会出现死循环,导致cpu100%,原因是1.7的resize会将原先节点的顺序倒过来。死循环问题的定位一般都是通过jps+jstack查看堆栈信息来定位的
1.8扩容时保持了原来链表中的顺序,避免了这个问题。
HashMap的table为什么是transient的
transient Entry[] table;也就是说table里面的内容不会被序列化,为什么?
对HashMap来说hashcode至关重要,而Object里hashcode是native方法public native int hashCode();。这意味着的是:HashCode和底层实现相关,不同的虚拟机可能有不同的HashCode算法。
Java的优势跨平台性,如果不用transient修饰table,那么便会失去这一特性。
来看看java重写的writeObject与readObject
private void writeObject(java.io.ObjectOutputStream s)
throws IOException {
int buckets = capacity();
// Write out the threshold, loadfactor, and any hidden stuff
s.defaultWriteObject();
s.writeInt(buckets);
s.writeInt(size);
internalWriteEntries(s);
}
void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
Node<K,V>[] tab;
if (size > 0 && (tab = table) != null) {
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
s.writeObject(e.key);
s.writeObject(e.value);
}
}
}
}
在writeObject选择将key和value追加到序列化的文件最后面
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException {
// Read in the threshold (ignored), loadfactor, and any hidden stuff
s.defaultReadObject();
reinitialize();
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new InvalidObjectException("Illegal load factor: " +
loadFactor);
s.readInt(); // Read and ignore number of buckets
int mappings = s.readInt(); // Read number of mappings (size)
if (mappings < 0)
throw new InvalidObjectException("Illegal mappings count: " +
mappings);
else if (mappings > 0) { // (if zero, use defaults)
// Size the table using given load factor only if within
// range of 0.25...4.0
float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f);
float fc = (float)mappings / lf + 1.0f;
int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ?
DEFAULT_INITIAL_CAPACITY :
(fc >= MAXIMUM_CAPACITY) ?
MAXIMUM_CAPACITY :
tableSizeFor((int)fc));
float ft = (float)cap * lf;
threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ?
(int)ft : Integer.MAX_VALUE);
// Check Map.Entry[].class since it's the nearest public type to
// what we're actually creating.
SharedSecrets.getJavaOISAccess().checkArray(s, Map.Entry[].class, cap);
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] tab = (Node<K,V>[])new Node[cap];
table = tab;
// Read the keys and values, and put the mappings in the HashMap
for (int i = 0; i < mappings; i++) {
@SuppressWarnings("unchecked")
K key = (K) s.readObject();
@SuppressWarnings("unchecked")
V value = (V) s.readObject();
putVal(hash(key), key, value, false, false);
}
}
}
在readObject的时候重构HashMap数据结构。
参考
推荐篇文章,图片丰富条例清晰,Java8系列之重新认识HashMap