一.什么是HashMap
HashMap是一种数据结构,它根据键的HashCade值,可以找到对应的值。HashMap查找值非常快,并且运行空值存在。HashMap在JDK1.7版本之前的存储结构是数组+单链表,在JDK1.8版本存储结构变为数组+单链表+红黑数。如下图所示
二.HashMap源码解析
2.1HsahMap的继承结构,属性,内部类和构造方法
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
HashMap继承于AbstractMap,继承的接口有Map,Cloneable,Serializable.
private static final long serialVersionUID = 362498820763181265L;
版本号
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
默认初始容量为16。
static final int MAXIMUM_CAPACITY = 1 << 30;
最大容量2的30次幂。
static final float DEFAULT_LOAD_FACTOR = 0.75f;
默认加载因子0.75.
static final int TREEIFY_THRESHOLD = 8;
链表转红黑树的阈值为8。
static final int UNTREEIFY_THRESHOLD = 6;
红黑树转链表的阈值为6.
static final int MIN_TREEIFY_CAPACITY = 64;
转红黑树,数组table的最小长度为64.
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;
}
}
链表节点继承于Entry。提供了三个对节点操作的方法。
transient Node<K,V>[] table;
table数组
transient Set<Map.Entry<K,V>> entrySet;
enterySet链表
transient int size;
int threshold;
阈值
final float loadFactor;
加载因子
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);
}
有参构造方法,初始容量小于0,抛出异常,初始容量大于最大的容量,初始容量等于最大容量。加载因子小于0或者对因子的判断,抛出异常。后面是加载因子的赋值和阈值的赋值。
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
这里是调用上面的构造方法
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
把加载因子赋值为0.75
2.2核心方法
2.2.1 putVal方法
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;
}
这个方法用于存储元素。上面这个代码很复杂,我们一步一步来解释。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
我们利用put传值进来其实是要调用这个putVal方法。
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
这里是判断table数组是否为空,数组长度是否为0,如果是则创建用resize方法创建一个新数组。
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
这里是通过n-1和hash的按位与运算算出插入的位置i,并判断插入位置是否为空,如果为空则对tab[i]进行插入。
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
如果不为空,判断原位置即table[i]是否和插入的key元素进看是否相同,如果相同进行替换。
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
如果不同,要先判断是否为红黑树,如果是则利用putTreeVal方法进行红黑树的插入。
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;
}
}
剩余的情况就是单链表,进行循环查找最后一个节点,找到了就插入。并判断插入后,binCount是否大于树化阈值即8,如果是进行树化。
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
* @param onlyIfAbsent if true, don't change existing value
如果插入的e不为空,e的值给oldValue,从注释可以看出onlyIAbsent如果是true,就不改变存在的值。这里判断flase或者oldValue为null,就把值进行覆盖。
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
这里是判断size是否大于阈值,大于则进行扩容。
2.2.2 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; // 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;
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;
}
这个方法就是扩容,我们一步一步来。
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
如果这个旧容量大于0,再判断这个旧容量大于等于最大容量,就把阈值设为整数的最大值。并返回旧容量,这里并没有进行扩容,这是容量太大的情况。
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);
}
如果新阈值等于0,,ft等于新容量乘以加载因子。如果新容量小于最大容量,并且ft小于最大容量,这里两个条件成立,新阈值就等于ft,否则就等于整数的最大值。
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
把新阈值赋值给当前的阈值,并创建一个新数组,赋值给table。
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
对旧数组的遍历。
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
把旧数组的第j个元素赋值给e,如果e不为努力,把旧数组下标为j的赋值为0。
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
如果e指向下一个节点的地址是不是为空(相当于只有一个节点),如果是,就把这个e存入新数组中,下标要通过e的哈希值于容量进行按位与进行计算。
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
如果e是树,就利用split进行拆分。
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);
先把e的哈希值于旧容量进行按位与计算,判断是否等于0,如果等再判断loHead这个链表是否为空,如果等于空,就把e传入loHead,否则就loTail指向下一个的地址为e。再把loTali赋值为e。如果不等于0,判断hiTail是不是为null,如果是就把hiHead赋值为e,否则hiTail指向下一个的地址为e,hiTail等于e。这个循环的条件为e等于下一个节点,并且不为空。上面这俩段代码就相对于把原链表拆分为两个链标。如果e的哈希值于键容量进行计算出来的是0,就放入loHead中,不为0放入hiHead中。
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
这里已经把链表拆分完了,就把loTail指向下一个节点的地址设为null,把newTab[j] 赋值loHead。
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
这里是把hiTail指向下一个地址为null,把newtTab[j+oldCap]赋值为jiHead。
2.2.3 getNode方法
*/
final Node<K,V> getNode(Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n, hash; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & (hash = hash(key))]) != null) {
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;
}
这个方法是获取节点。
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & (hash = hash(key))]) != null)
判断数组是否为空,不为空进行下面的操作,为空返回null。
f (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);
判断第一个元素指向下一个节点地址是否为空,不为空就进行下面的操作,判断第一个元素是不是树,是就利用getTreeNode去获取树中对应的值。
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
这里的情况就是单链表的情况,循环去查找,找到了,就返回该元素。循环条件是e指向下一个节点的地址不为空。
3.总结
1.putVal方法用于存储,传入的键-值对,对键进行运算,运算出来的哈希值先存放到下标为数组长度和哈希值进行按位与进行计算出来的。但不同的键可能算出来相同的哈希值,这种情况,就才用单链表存储,如这种情况的个数超过了8,就变成了红黑树。从上面的源码我们也可以看出HashMap的特点,存储同键不同值的时候,后面的值会把前面的值覆盖。可以允许null的存在。
2.resize方法用于扩容,从源码我们可以看出,扩容会变成原来容量的俩倍,阈值也变成原来的俩倍。这是一般情况。
3.getNode方法用于获取元素,只要的是对插入元素的判断,有三种情况,第一个元素,红黑树,链表。