HashMap基于哈希表,实现 Map 接口,以键值对形式存储数据,它的键 key 不可重复但可以为 null,值 value 可以重复可以为 null,元素存取无序,并且存储元素时如果已经有该键会采用新值覆盖旧值的策略。
由于HashMap是基于哈希表实现的,而哈希表随着数据的增加一定会出现哈希冲突的问题(鸽巢原理),解决哈希冲突的方式主要有两种:(1)开放地址法:产生哈希冲突时,重新探测一个新的空闲位置将其插入,适用于数据量小的情况。(2)拉链法:在冲突位置建立链表,并将其插入链表。
HashMap采用拉链法解决哈希冲突,它的数据结构是 数组 + 链表,JDK1.8以后它的数据结构是 数组 + 链表 + 红黑树
put()一个元素的过程:
1. key 的 hashCode 经过扰动函数处理后得到hash值;
2.通过 length 减 1 按位与hash值计算当前元素存放的位置;(length指数组长度);
3.如果数组某个位置为null,直接new Node对象,将Node对象存储到计算的位置;
4.当计算出的存储位置上已经有元素,判断链表长度,如果没有转为红黑树,将元素插入链表,如果已经转为红黑树,那就插入树中。
当链表长度 >=8 且 数组长度 >64,链表才会转为红黑树
第一次扩容会在元素个数达到 12 时进行,扩容的大小为原来的 2 倍
HashMap的最大容量是 Integer.MAX_VALUE,也就是 2 的 31 次方减 1
JDK1.8:
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 哈希数组长度默认16
static final float DEFAULT_LOAD_FACTOR = 0.75f; // 负载因子0.75
static final int TREEIFY_THRESHOLD = 8; // 树化阈值
static final int UNTREEIFY_THRESHOLD = 6; // 链表还原阈值
static final int MIN_TREEIFY_CAPACITY = 64; // 最小树形化容量阈值
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数组未初始化或长度为0,初始化、扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length; //resize()既初始化又扩容
// 计算数组索引下标,如果为null直接插入
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 当hash值一致,键一致,说明该键在table中已存在,使用e保存(后边会实现新旧值替换逻辑)
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;
}