一、HashMap基本源码实现
1、HashMap基本结构
HashMap继承AbstractMap抽象类,AbstractMap实现Map接口。
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
private static final long serialVersionUID = 362498820763181265L;
....
}
public abstract class AbstractMap<K,V> implements Map<K,V> {
protected AbstractMap() {
}
...
}
二、HashMap的基本数据结构
jdk1.8之前,HashMap是由“数组+链表”的结构组成,jdk1.8之后,HashMap得到很大的改善;数据结构也发生了改变:“数组+链表+红黑树”;当链表节点大于8时,会转换为红黑树;否则仍然以链表结构。

- 头节点指的是table表上索引位置的节点,也就是链表的头节点
- 根节点(root节点)指的是红黑树最上面的那个节点,也就是没有父节点的节点
- 红黑树的根节点不一定是索引位置的头节点
- 转为红黑树节点后,链表的结构还存在,通过next属性维持,红黑树节点在进行操作时都会维护链表的结构
- 在红黑树上,叶子节点也可能有next节点,因为红黑树的结构跟链表的结构互不影响
三、HashMap的工作原理
1、定位哈希桶数组索引位置
不管增加、删除、查找键值对,定位到哈希桶数组的位置都是关键的一步。HashMap定位数组的索引位置,直接决定了Hash方法的离散性能。下面为定位哈希桶数组源码:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
int n = tab.length;
int index = (n-1) & hash;
整个过程主要分为三步:
- 拿到key的hashCode值
- 将hashCode的高位参与运算,重新计算hash值
- 将计算出来的hash值与(table.length - 1)进行&运算
2、HashMap的put方法实现
源码如下:
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;
}
思路如下:
- table[]是否为空
- 判断table[i]处是否插入过值
- 判断链表长度是否大于8,如果大于则转换为红黑二叉树,并插入树中
- 判断key是否与原有的key相同,如果相同就覆盖原有key的value,并返回原有value
- 如果key不相同,就插入一个key,记录结构变化一次
3、HashMap的get方法实现
源码如下:
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != 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;
}
思路如下:
- 判断表或key是否为null,如果是直接返回null
- 判断索引处第一个key与传入key是否相等,如果相等直接返回
- 如果不相等,判断链表是否是红黑二叉树,如果是,直接从树中取值
- 如果不是树,则遍历链表查找
4、HashMap扩容机制
HashMap扩容可以分为三种情况:
第一种:使用默认构造方法初始化HashMap。HashMap一开始初始化的时候会返回一个空的table,并且thershold为0.因此第一次扩容的容量为默认值DEFAULT_LOAD_FACTOR = 12。
第二种:指定初始容量的构造方法初始化HashMap。下面源码可以看到初始容量会等于threshold,接着threshold = 当前容量(threshold) * DEFAULT_LOAD_FACTOR。
第三种:HashMap不是第一次扩容,如果HashMap已经扩容过的话,那么每次table的容量以及threshold量为原来的两倍。
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;
}
来源:https://www.cnblogs.com/xudongsheng0721/p/11996039.html