HashMap基于哈希表实现的,每一个元素都是一个 key-value 对,内部通过单链表解决冲突的问题。
HashMap不是线程安全的,ConcurrentHashMap 是线程安全的。
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
HashMap 继承自 AbstractMap 类,同时实现了 Map,克隆,序列化的接口。
HashMap,在 Java7 中,是由数组和链表实现的,当元素的哈希值计算后,落在哈希值数组对应的桶中,如果有多个元素落在同一个桶中,那么就用链表来解决冲突,节点可以往后一直添加。
而在 Java8 中,JDK 对 HashMap 做了较大改动,引入了红黑树。即对链表部分的结构进行了优化,采用了链表或者红黑树的结构。
结构如图示意:
下面根据源码进行说明:
常量
// 默认的初始容量为16,其必须为2的整数次方
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 最大容量,2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认的加载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// Java8中链表转树的阈值8
static final int TREEIFY_THRESHOLD = 8;
// Java8中树转链表的阈值6
static final int UNTREEIFY_THRESHOLD = 6;
// Java8中转树时数组容量最小值
// 当桶数量太小时,而一个桶中超过8个,此时应该先数组扩容而不是转树
// 为了避免转树还是扩容的冲突,这个值不能小于4*TREEIFY_THRESHOLD
static final int MIN_TREEIFY_CAPACITY = 64;
单向链表类
Node<K,V> 存储了当前元素和指向下一个元素的指针。
// 链表中的节点类,属性有哈希值,key,value,下一个节点指针
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;
}
// 如果两个元素key和value都相同,就返回true
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;
}
}
变量
// 单向链表构成的数组
transient Node<K,V>[] table;
// 底层数组中已使用的桶的数量
transient Set<Map.Entry<K,V>> entrySet;
// 底层数组中已使用的桶的数量
transient int size;
// 结构变化的快速失败变量,修改结构时自增加一
transient int modCount;
// 调整容量的阈值,(阈值=容量*加载因子)
int threshold;
// 加载因子的实际大小
final float loadFactor;
构造函数
给定初始容量和加载因子的构造函数。
阈值的计算由 tableSizeFor 函数来计算,返回比给定值大的第一个 2 的整数幂的值。
tableSizeFor 函数:
该函数有 4 次异或运算,比如 0…01XXXXXX 这个整数:
1. 第一次 n 和 n 右移一位后异或,即 01XXXXXX 和 001XXXXX 异或,为 011XXXXX;
2. 第二次 n 和 n 右移二位后异或,即 011XXXXX 和 00011XXX 异或,为 01111XXX;
3. 第三次 n 和 n 右移四位后异或,即 01111XXX 和 00000111 异或,为 01111111;
4. 第四次异或后结果为 01111111,n = n + 1 ,所以自然结果为 10000000;
5. 可以看到比 01XXXXXX 大的第一个 2 的整数幂的值就求出来了。
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);
}
// 根据设置的初始容量计算阈值的方法
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
其他几个构造函数不在详细说明。
主要方法
resize()
final Node<K,V>[] resize() {
// 当前table赋给oldTab
Node<K,V>[] oldTab = table;
// 旧数组长度oldCap
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 旧的阈值oldThr
int oldThr = threshold;
// 定义新数组长度,新阈值
int newCap, newThr = 0;
// 旧数组长度大于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;
}
// 旧数组为空,阈值大于0,就将旧门限作为新的数组长度
else if (oldThr > 0)
newCap = oldThr;
// 旧数组为空,阈值也为0,此时根据初始默认值重新初始化数组容量和阈值即可
else {
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 如果新阈值等于0,那么重新赋值,新数组容量和加载因子相乘作为阈值
// 这里新数组长度大于最大长度或者新阈值大于最大长度,就直接把最大整数赋值给新阈值即可
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
// 新阈值计算完毕,作为HashMap的阈值
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
// 定义了一个新数组,数组大小为newCap
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) {
// 下标有元素不为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;
// 这里hash和oldCap做与运算,是为了根据哈希值重新让元素落入倍增后的各个桶中
// 比如之前16的容量,倍增后32
// 以15为例,00001111和00010000与操作后,得到0不需要改变桶中位置
// 以17为例,00010001和00010000与操作后,得到1需要改变桶中位置,1+16=17
// 即原来16的容量,17的hash需要映射为1,而扩容后,容量大了,可以映射为17
// 所以这里的与操作是与oldCap确定是否需要移动而不是与(oldCap-1)来确定位置
// 这里就可能要将原来桶中的单链,拆为2条链,一条低位置桶的链,一条高位置桶的链
if ((e.hash & oldCap) == 0) {
if (loTail == null)
// 低位置桶的链的第一个元素
loHead = e;
else
// 每个新元素都接在单链表的尾部
loTail.next = e;
// 每一次loTail都重新指向循环的单链表的当前元素
loTail = e;
}
else {
// 高位桶的新的单链表和地位桶的同理
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
// 循环结束后,低位桶的单链表尾节点的下一节点置null
loTail.next = null;
// 低位桶的单链表首元素放于未改变下标的桶中
newTab[j] = loHead;
}
if (hiTail != null) {
// 高位桶的单链表尾节点的下一节点置null
hiTail.next = null;
// 高位桶的单链表首元素放于改变了下标的新桶中
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
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;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
// 如果hash对应桶中的节点为空,说明桶中尚无节点,此时新加节点即可,此时不用考虑是单链表或树结构
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))))
// 如果桶中有节点,切第一个节点的key就和要插入的key相同,说明已存在同样key
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) {
// 循环到单链表最后的节点也没有找到对应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;
}
}
// 已经有key-value的映射的情况下
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
// 结构变动需要modCount这个快速失败的验证字段自增加一
++modCount;
// 如果增加节点后的HashMap元素个数大于HashMap阈值,需要调整容量
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
get方法
public V get(Object key) {
Node<K,V> e;
// 根据key的hash值来获取目标节点
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;
// first是hash指对应桶中的第一个元素
// (n-1)&hash,n为2的整数幂的值,比如16,那么15就是1111,保证hash的每一位都能参与运算,结果更离散
// (如果这里有0,那么不管0还是1和0做与运算结果都是0,会造成多个值落在同一个桶中,不能实现更好的哈希离散)
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 找到了hash对应桶中的第一个节点,那么如果这个节点key就是要找的,那么返回该节点即可
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
// first不是要找的,那么找first的下一个节点
if ((e = first.next) != null) {
// 如果第一个节点是树节点,那么说明这个不是单链表,而是红黑树,用树节点查找方法继续查找
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
// 单链表的情况下,一直向链表尾部遍历即可,直到发现对应的key返回节点即可
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}