HashMap
常量
/**
* 初始容量16,写作1 << 4是为了提示这是2的四次方
* 初始容量如果过小会造成频繁的扩容,初始容量如果过大会造成内存浪费
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 最大容量必须为2的幂
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 默认的负载因子
* 均衡了时间和空间损耗算出来的值,较高的值会减少空间开销但增加了查找成本
* 较小的值会造成空间浪费
* 不扩容的条件:数组容量 > 需要的数组大小 /load factor
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 链表转换为红黑树的链表长度阈值
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 红黑树转换为链表的阈值
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 链表转换为红黑树的数组长度阈值,如果数组长度小于64会先选择扩容
*/
static final int MIN_TREEIFY_CAPACITY = 64;
结点数据结构
static class Node<K,V> implements Map.Entry<K,V> {
//节点hash
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;
}
}
属性
//如果存在并发修改会进行快速失败
transient int modCount;
//hashmap的实际大小
transient int size;
//存放节点的数组
transient Node<K,V>[] table;
//扩容阈值
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;
//设置初始扩容阈值为大于initialCapacity的最小2的幂
this.threshold = tableSizeFor(initialCapacity);
}
//使用默认的负载因子赋值0.75
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
//返回大于cap的最小2的幂
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;
}
新增方法
/**
* hash 通过哈希算法算出的hash值
* key 键值
* value 放置的值
* onlyIfAbsent 这个值为true时如果存在映射并且value不为空则不进行替换
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果数组为空,resize初始化数组
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;
// 需要插入的key与头节点的key相同时
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;
}
}
//存在key
if (e != null) { // existing mapping for key
V oldValue = e.value;
//当 onlyIfAbsent 为 false 时,才会覆盖值
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
// 返回老值
return oldValue;
}
}
// 记录 HashMap 的数据结构发生了变化
++modCount;
//如果 HashMap 的实际大小大于扩容的门槛,开始扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
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;
}
//扩容:数组长度*2、扩容阈值*2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0)
//如果给定有初始阈值则用初始阈值设置数组大小
newCap = oldThr;
else {
//初始阈值为零使用默认值16赋值,并且将扩容阈值设置为16*0.75
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
//这里创建了两个头两个尾是因为元素下标在扩容后要么是原下标+oldcap要么不变
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;
}
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//如果数组长度小于64先进行扩容
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
查找方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
//获取对象hash值,这里将高16位传播到了低16位,使得即使在小表中高16位也会影响到元素在数组中的位置
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
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
//如果第一个元素和对应的key相等则返回头节点
((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;
}