HashMap继承和实现
由源码可以看出来HashMap继承AbstractMap抽象类,并实现了Map、Cloneable、Serializable接口,而AbstractMap抽象类实现了Map接口。
结构组成
在JDK7版本中HashMap是由数组+链表组成的,而在JDK8中HashMap是由数组+链表+红黑树实现的,对于原因在后面会讲到,如图所示;
注:图来源于美团点评技术团队
HashMap类的属性
Node[] table数组:通俗讲就是哈希桶,table的大小必须是2的n次方,默认长度时16。
size:实际存在的键值对的数量;
modCount:主要用来记录HashMap内部结构发生变化的次数,主要用于迭代的快速失败。
threshold:键值对阈值,也就是容纳键值对的最大数量;
loadFactor:负载因子,默认值时0.75,建议不要随便修改。
这其中的关系是:threshold = table.length * loadFactor。
存储原理
通过源码可以看到Node[] table数组是个很重要的属性,看源码:
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;//key的哈希值,数据存储的位置
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 是一个内部类,本质就是一个键值对。
数据是如何存储的?
当存入这样的数据时,map.put("东墙","我是东墙")时,系统会调用“东墙”这个key的hashCode()方法来计算这个key的hash值,然后在通过hash算法的后两步运算来获得存储的位置,有时不同的key会计算出相同的索引值,也就是会定位到相同的位置,这时候会发生哈希碰撞。所以当table的长度越大时,碰撞的几率就越小,但要考虑性能的问题,所以就需要好的哈希算法和扩容机制。在这里使用链地址法来解决哈希碰撞的问题。当索引值相同时,后来的数据会链在之前的数据之后。
索引的位置的计算方式
在源码中,有这几行代码可以看到怎么计算的索引值的:
static final int hash(Object key) {
int h;
// h = key.hashCode() 为第一步 取hashCode值
// h ^ (h >>> 16) 为第二步 高位参与运算
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
总结下来就是,取key值hasCode值、高位运算、取模运算。在这里使用(n-1)& h来计算模值(h%length)是非常好的,提高了速度,因为&的性能比%的要快,算法举例说明:
HashMap的put()方法是如何工作的?
这里借鉴其他人的图解:
我们可以看源码来进行解读:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);//对key进行计算哈希值
}
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)//1.table为空时,调用resize()方法进行扩容
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)//2.计算索引值,并判断此位置上是否有数据
tab[i] = newNode(hash, key, value, null);//3.没有则添加此数据
else {//4.此位置上有数据
Node<K,V> e; K k;
if (p.hash == hash &&//5.判断key是否存在,存在则直接覆盖
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)//6.判断链是否时红黑树
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {//7.链为链表
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
treeifyBin(tab, hash);//链表长度大于8则转换为红黑树
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;//key已经存在,则直接覆盖
}
}
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;
}
为什么要加入红黑树?
即使负载因子和Hash算法设计的再合理,也会出现链表过于长,会影响性能,所以当链长度大于8时,会转换为红黑树,红黑树结合了数组和链表的有点,易查询和易修改。
HashMap的扩容机制
我们还是结合源码来进行分析
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) {//最大容量为2^30
threshold = Integer.MAX_VALUE;//当为最大容量时,不再扩容,为int的最大值2^31-1
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)//容量大于16小于最大值时容量扩大2倍
newThr = oldThr << 1; // double threshold//阈值也扩大2倍
}
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;
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;
}