1. HashMap原理
2. HashMap源码分析
3. HashMap在java8中的改变
hashmap原理
HashMap简单来说就是一个散列表,存储着key-value键值对
HashMap的存储结构是一个数组加链表的结构,在java8之后链表在长度超过TREEIFYTHRESHOLD树化阈值且map中的元素数量超过了MINTREEIFY_CAPACITY最小树化容量,则会转化成红黑树的结构
HashMap通过hash算法使在不考虑hash冲突的情况下查找方法的时间复杂度为O(1)
hashmap源码分析
hashmap的初始化
hashmap的初始默认容量是16,如果超过阈值则会扩容,在扩容的时候要重新计算hash值将其放入新的hashmap中,因此扩容操作是一个相当耗时的操作,我们在使用的时候应该根据实际需要指定初始容量,尽可能避免扩容
..
/**
* 指定初始容量的构造函数
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* 无参构造函数的初始负载因子是0.75,默认容量是16
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
put方法
hashmap在初始化的时候并不会去初始化数组,只有在put第一个元素的时候才会去初始化数组
put的流
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;
//判断table是否为空,table为空则进行初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//判断索引位置有无元素,如果没有则创建node对象,存入该元素
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//如果该位置存在元素,且key值相同,则替换值
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)//hash值一样,但是key不同,且链表为红黑树结构,则往树中加入该元素
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
//链表最后都没有key相同的元素,则在链表的最后加入该元素
p.next = newNode(hash, key, value, null);
//如果超过树化阈值,则将链表树化
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果链表中有key相同的元素,则退出循环
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//e不为空则个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;
}
get方法
get流程图
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;
// 判断table是否为空,table在该节点位置是否为空
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 判断该位置的第一个元素的key值是否和get的key值相等
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 判断是否有下一个节点
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;
}
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; // 容量扩大两倍
}
else if (oldThr > 0) // 如果数组为空,指定了新增阈值-->带参初始化
newCap = oldThr;
else { // 数组为空,没有指定新的阈值,采用默认初始值-->无参初始化
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 { // 单链表节点,将原数组中的链表元素拆分,一部分在原索引位置,一部分在原索引加原数组长度
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) { //哈希值与原数组长度进行&操作,为0则在原数组位置,非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;
}
hashmap在java8中的改变
hash冲突的时候的单链表在java8中超过阈值会转化为红黑树,优化了查找速度
在链表插入由头插法改成了尾插法,是由于原本的头插法在扩容时,高并发下会导致链表成环的问题,而尾插法扩容时会保持链表元素的顺序
引用参考 [1]https://blog.csdn.net/u013494765/article/details/77837338 [2]I am CR7的公众号