原理
- HashMap的实现用到了数组、链表、红黑树(二叉查找树):最外层是Node数组,数组的某一位置可能是单个节点,也可能是链表或红黑树,由这个哈希索引对应的元素多少而定。
- 键值对在数组中的位置根据hashcode运算得到
- 高位与低位异或
- 对数组容量求余(位运算&实现,因数组容量总是2的幂)
- 数组容量随键值对的实际数量扩增
put方法
put方法用于添加键值对
数组为null时,调用resize创建初始容量的数组,初始容量为16
-
找到key的哈希索引位置后,比较key可hash值,和Equal方法,判断key是否已存在
- 不存在将键值对放入对应位置
- 已存在更新原有值。
索引对应位置,有多个元素时,以链表形式保存,内部类Node有next属性;当元素超过一定数量时,改为红黑树存储,节点类型为TreeNode。TreeNode继承自Node的子类LinkedHashMap.Entry<K,V>。
改变modCount属性、size属性,size大于阈值threshold时,调用resize方法,扩大容量。threshold有数组容量和负载因子决定,一般为数组容量的75%。
-
返回值:
- 若key已存在,返回旧值
- 若key不存在,返回null
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)
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;
}
resize方法
- 数组为null时,创建初始容量的数组,初始容量为16
- 扩大数组容量(创建更大容量的新数组),一次扩大2倍,最大为2的30次方
- 扩大容量后,对原有键值对,重新计算索引,移动位置。
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;
}
特点
- 查找效率很高,时间复杂度近似于1
- 添加效率低不稳定,可能需要扩容,移动原有元素
- 多线程不安全。ConcurrentHashMap线程安全,多线程时建议使用。
参考
- Java HashMap原理详解
- 为什么HashMap线程不安全