HashMap源码分析
2019-04-01 本文已影响0人
冷冷DerFan
HashMap源码分析
本文对jdk1.8的HashMap做了分析
首先看一下HashMap的继承图:
HashMap继承树.png1.实现了Map接口,扩展内部方法
2.实现了Cloneable接口,可复制
3.实现了Serializable接口,可以被序列化
数据结构
jdk1.8的HashMap是数组+链表+红黑树来实现的,其中数据成员如下:
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;
}
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的数组
transient Node<K,V>[] table;
transient Set<Map.Entry<K,V>> entrySet;
// 实际存储k-v对数
transient int size;
// 被修改的次数
transient int modCount;
// 存储的k-v对个数阈值
int threshold;
// 加载因子
final float loadFactor;
初始化时,主要完成了loadFactor和threshold的初始化。默认初始化时HashMap的threshold为16,loadFactor为0.75f。
构造函数
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);
}
可以看到这里初始化了loadFactor,使用tableSizeFor初始化了threshold,使用位运算高效地返回了比initialCapacity大的 最小的2的整数次幂等。
值得注意的是在这里的threshold是hash桶数组的长度,在第一次进行put操作时,还会进行resize操作,将threshold重新赋值。该值为 loadFactor * threshold 0.75 * 16
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;
}
put方法
默认put方法中会先通过性能优越的hash函数来计算哈希值
计算Key的hash值
static final int hash(Object key) {
int h;
// h ^ (h >>> 16) h的高16位和低16位抑或,位运算效率更高
// int32位,扰动函数,使得高16位和低16位的变化都会对结果造成影响
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
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;
// tab为空则需要初始化一个
if ((tab = table) == null || (n = tab.length) == 0)
// 初始化和resize都调用resize
n = (tab = resize()).length;
// 计算位置,取出元素判断,为空则插入一个新的元素
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 元素不为 null
else {
Node<K,V> e; K k;
// p为已存在的Node 判断插入元素和 p hash值相同,key相同,则后面会新元素替换老元素
// 此处先拿出老元素 p 赋值给 e
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);
// 链表长度大于8则转化为红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
// 实际此方法中判断table长度< 64 会resize
// 只有链表长度大于8,并且table长度>= 64会转化为红黑树
treeifyBin(tab, hash);
break;
}
// 判断插入元素key已经存在,则退出循环,遍历到的元素为e
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;
// key已经存在,则新的 value 替换老 value
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 元素个数超过容量阈值则扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
* 链表转化为红黑树
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// tab为null则初始化数组 tab长度<64则resize,都调用resize()
// 但不会转化为红黑树
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
// tab不为null,tab长度>64 转化为红黑树
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);
}
}
/**
* 初始化或者resize 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) {
// 容量 >= 1 << 30
if (oldCap >= MAXIMUM_CAPACITY) {
// 容量设为 2 ^ 31 - 1
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 没超过最大值,则扩容为原来的2倍
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;
// 旧的容量为0,则使用默认值初始化
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;
}
扩容机制
1.当容量为0,初始化为 DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY 16 * 0.75
2.容量超过最大值,赋值为最大值
3.原有没超过最大值,且实际Node个数大于阈值threshold,则数组扩容为原来的两倍,元素重新排序
以上讲述了HashMap的put方法,解决哈希冲突的拉链法,以及红黑树的转换,扩容机制等的源码分析。