hashmap底层是基于数组加链表实现的,数组是主干,链表主要是为了解决hash冲突存在的。我们通过put()和get()方法储存和获取对象。当我们将键值对传递给put()方法时,它调用键对象的hashCode()方法来计算hashcode,让后找到bucket位置来储存Entry对象。当获取对象时,通过键对象的equals()方法找到正确的键值对,然后返回值对象。HashMap使用链表来解决碰撞问题,当发生碰撞了,对象将会储存在链表的下一个节点中。 HashMap在每个链表节点中储存键值对对象。
下面对部分源码进行分析
1.属性介绍:
- 初始容量为2^4=16,hashMap的数组长度必须是2的次方 *,扩展长度时是当前长度 << 1
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
- 最大容量为2^30
static final int MAXIMUM_CAPACITY = 1 << 30;
- 负载因子为0.75 ,当元素个数超过这个比例(即当前容量*0.75),则会执行数组扩充操作。
static final float DEFAULT_LOAD_FACTOR = 0.75f;
- 树形化阈值,链表长度为8时,进行树形化,将链表转为红黑树
static final int TREEIFY_THRESHOLD = 8;
- 解除树形化阈值,红黑树的节点个数为6时,将红黑树转为链表
static final int UNTREEIFY_THRESHOLD = 6;
- 最小树形化的容量,即:当内部数组长度小于64时,不会将链表转化成红黑树,而是优先扩充数组
static final int MIN_TREEIFY_CAPACITY = 64;
2.put方法
当往hashmap里put(key,value)新元素时,
- 利用key计算出hash值,然后再计算下标;求解下标的具体过程为:得到key.hashcode进行高16位^低16位,得到hash值;根据下标index=(n - 1) & hash,即可计算出下标。
- 放入节点时,有以下4种情况(源码中用4个if、else实现):
- 数组原本位置为空,直接放入。
- 数组原本位置不为空,且下面连接了链表,往链表中添加节点,当链表长度为8时,进行树形化,将链表转为红黑树。
- 数组原本位置不为空,且下面连接了红黑树,往树中添加节点,当红黑树的节点个数为6时,将红黑树转为链表。
- 数组原本位置不为空,但要放入的节点的key与当前节点的key相同,则进行值覆盖,用新值替换旧值。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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;
}
注意:
- 链表进行树形化时,要先判断当前数组长度是否达到了最小树形化的容量,即:当内部数组长度小于64时,不会将链表转化成红黑树,而是优先扩充数组。(因为存在这样一种情况,数组长度很小,使得大量节点需要放在一个地方,此时不需要进行树形化,只需将数组进行扩容)。
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();
hash的实现:
hash值是根据hash算法(key.hashcode进行高16位与低16位进行异或)确定的。
- 高16位与低16位:是为了避免没有高位参与运算引起的碰撞。
- 异或:因为异或属于逻辑运算,在硬盘上实现的,运算速度快,像+、-、这种都属于算数运算,速度较慢。
3.扩容机制
HashMap出现扩容有两种情况:
-
在扩容的时候,首元素达到阈值了,即当前容量*0.75。
-
hashMap准备树形化但发现数组太短,即小于最小树形化的容量。
当扩容时有两种情况:
-
当前容量已达最大,即长度已经为2^30,则不进行扩容,返回当前数组。
-
否则,在现在基础上扩大二倍
为什么以2的n次幂进行扩容?
在hashmap中数组下标的确定是通过index=(n-1)&hash计算的,2^n换成二进制都是“100000....”这种形式,减一后都是“011111..”.这种除了第一位后面几位都是1的二进制数
-
这样的话,相当于hashmap的位置,就只和hashcode的值有关,算出来的index是分布均匀的。
-
当不全为1,出现“01101”这样的形式,那么与0对应的那一位,不论hashcode值是0还是1,进行与运算后,都会放入同样的位置,这样会大大增加hash冲突。
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
}
当进行扩容后,原来的节点也需要往新的数组挪动
向扩容后的数组挪动的时候有以下3种情况
-
只有一个节点 :将当前节点置空后,新的位置=hash & (newCap - 1)
-
数组下有链表:原下标+原容量
-
数组下有红黑树:进行分割
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;
}
}
}
}
}
4.快速失败(fail-fast)
java.util下的集合类都是fail-fast的,它是java集合中的一种错误检测机制,某个线程多hashmap进行迭代时,不允许其他线程对其做结构性的修改(如remove()方法),否则就会抛出 ConcurrentModificationException
public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
在遍历过程中,HashIterator的remove方法不会导致快速失败,HashMap的remove方法才会导致(也就是我们平时经常调用的)
fail-fast原理:modCount表示修改次数,expectedModCount也是修改次数,初始与modCount相同,HashIterator的remove等方法会修改它的值HashMap的remove方法不会修改expectedModCount,但会修改modCount,当二者不同时,就会抛出 ConcurrentModificationException
HashIterator的remove方法:
public final void remove() {
Node<K,V> p = current;
if (p == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
current = null;
K key = p.key;
removeNode(hash(key), key, null, false, false);
expectedModCount = modCount;
}
HashMap的remove方法:
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
![点击并拖拽以移动 wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==](https://img-blog.csdnimg.cn/2022010614530514364.gif)