HashMap源码:
1.构造函数:
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
new HashMap时,无参构造会默认创建初始化桶为16,加载因子为0.75的HashMap,但不会立即初始化,采用懒加载策略
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
2.put源码:
//传入K,V值,在其中调用了putVal()方法
//先算出key的hash值,然后将K,V值传入,后边俩个boolean值分别表示:
//onlyIfAbsent:如果为真,则不会改变已经存在的value值
//evict:如果为假,则哈希表为创建状态
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
2.1–putVal:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
//方法的全局变量,tab表示当前的hashTable
//p表示:哈希表中桶的链表(红黑树)节点
//n:tab的长度
//i:存放哈希得到的桶下标
Node<K,V>[] tab; Node<K,V> p; int n, i;
//取得当前的哈希表,如果当前哈希表还未创建,执行
if ((tab = table) == null || (n = tab.length) == 0)
//调用resize()初始化hashTable
n = (tab = resize()).length;
//现在tab一定已经初始化了
//根据key值哈希后的得到的桶下标,并且此时桶中元素个数为空
if ((p = tab[i = (n - 1) & hash]) == null)
//将将要保存的节点放置在此桶的第一个元素
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//如果当前节点的hash与key的hash相等
//且(当前节点的key == key ||
//(key不为空&& key与p.key相等)
//语义为:当当前桶节点的key和要添加元素的key相同且不为空时,
//将p节点赋值给e节点,e节点后边会进行判断
//节点处于同一个桶中,且头结点key值完全一样,替换头结点
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果p节点已经被成为树节点,就把p节点强转为treeNode
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;
//判断添加元素后,整个的哈希表大小是否超过threshold
//如果超过,调用resize()扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
2.2put流程:
-:若HashMap还未初始化,先进行哈希表的初始化操作(默认16个桶)
–:对传入的key值做hash,得到要存放该元素的桶编号
a:若没有发生碰撞,即头结点为空,将该节点直接存放到桶中
b:若发生碰撞:
1.此桶中的链表已经树化:直接将节点构造为树节点后直接加入红黑树
2.此时链表还未树化:将节点尾插入链表
—:若哈希表中存在key值相同的元素:替换
----:若桶满:调用resize()扩容哈希表。
3.get源码:
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//判断表是否为空,表的长度是否大于0,要get的key的hash值是否为空
//只有有一项不满足,直接返回null
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
//当前节点的key值刚好是桶的第一个节点
return first;
//遍历桶的其他节点,找到指定key,返回value
if ((e = first.next) != null) {
//树的遍历
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//链表的遍历
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
3.2get方法流程:
-:当表还未初始化或key为null,return null
–:表已经初始化,且key不为null
a:key值刚好是桶的头结点,返回
b:遍历桶中其他节点
-:若已经树化,调用树的遍历方式找到指定key对应的Node返回
-:调用链表的遍历方式查找指定key对应的node返回
4.扩容resize():扩容为原来的2倍(桶的个数)
4.1:负责哈希表的初始化操作
4.2:当表中元素个数达到阈值:容量 * 负载因子,后进行扩容
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;
//对原哈希表的元素进行rehash
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;
}
4.3扩容后,原来元素进行rehash:要么元素还呆在原桶中,要么待在double桶中
5.性能问题:
多线程下:在竞争激烈的场景下,使用hashmap会造成cpu爆满,(使用concurrenthashmap解决)
性能主要开销:resize()后的rehash过程
解决:在能预估存放元素个数的前提下,传入适当的初始化参数,尽量避免resize()