1 HashMap
HashMap 是我们日常开发中常用的集合类,怎么用我们都知道,那它的内部原理是啥?本文带大家了解一下,抛砖引玉哈
1.1 类图
1.2 属性介绍
/**
* 默认容量16
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 最大容量2的30次方
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 装载银子
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 链表转红黑树阀值,> 8 链表转换为红黑树
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 树转为链表的的阈值 6
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
*
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/*
* 存储的数据
*/
transient Node<K,V>[] table;
/**
*
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* 个数
*/
transient int size;
/**
* 说明hashMap是快速失败 (See ConcurrentModificationException).
*/
transient int modCount;
/**
* The next size value at which to resize (capacity * load factor).
*
*
*/
int threshold;
/**
* The load factor for the hash table.
*/
final float loadFactor;
1.3 内部类
1.3.1 内部类 Node
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;
}
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;
}
}
Node 类是单链表模式
1.3.2 内部类TreeNode
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
}
static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
1.4 构造方法
1.4.1 默认构造方法
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // 其他属性均采用默认值
}
1.4.2 指定容量HashMap(int initialCapacity)
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
1.4.3 指定容量和装在因子 HashMap(int initialCapacity, float loadFactor)
public HashMap(int initialCapacity, float loadFactor) {
// 1
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//2
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
// 3
this.threshold = tableSizeFor(initialCapacity);
}
static final int tableSizeFor(int cap) {
// 扩容门槛为传入的初始容量往上取最近的2的n次方
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;
}
- 判断初始化容量,如果
<0则抛出异常,如果>MAXIMUM_CAPACITY,则初始容量 =MAXIMUM_CAPACITY - 校验装载因子有效性
- 计算扩容门槛 -- 传入的初始容量往上取最近的2的n次方
1.5 操作方法
1.5.1 添加元素put(K key, V value)
public V put(K key, V value) {
//1 调用hash(key)计算出key的hash值
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
//1 如果key为null,则hash值为0,否则调用key的hashCode()方法,并让高16位与整个hash异或,这样做是为了使计算出的hash更分散
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab;
Node<K,V> p;
int n, i;
//2
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//3
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//4
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//5
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//6
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;
}
}
//7
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//8
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
- 调用
hash(K key)计算出key的hash值, - 将
table赋值给tab,如果tab为null 或者长度n ==0,调用resize()对tab进行初始化,并将扩容后的长度赋值给n - 通过
(n-1) & hash计算该key应该落入的桶,如果该桶中无数据,则把该数据放入桶中的第一个位置(新建一个Node) - 如果桶中的第一个元素的key和待插入的key值相同,则将桶中第一个元素保存给e,后续使用
- 如果第一个元素是
TreeNode, 则调用putTreeVal(this, tab, hash, key, value)插入 - 将该桶对应点链表的长度赋值给
binCount,并进行遍历,将p.next赋值给e,如果 待插入的key在存在于链表中,说明找到了和待插入元素相同key的元素,则跳出循环,进行p=e操作,反之,则说明链表中无相同key,在p后面进行新加元素,然后进行判断是否需要 树化,注意 这里之所以用TREEIFY_THRESHOLD - 1去判断,因为 因为第一个元素没有加到binCount中 - 如果有相同的元素,用
oldValue保存原始值,并根据!onlyIfAbsent || oldValue == null进行判断是否进行元素覆盖。并返回oldValue(这点之前并没有注意到), 其中afterNodeAccess是节点被访问后的后续操作,LinkedHashMap中游用到 - 走到这一步说明没有找到相同值,进行
++modCount操作,标志着HashMap快速失败,判断是否需要扩容
附上流程图
1.5.2 扩容resize
final Node<K,V>[] resize() {
//1
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
//1
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)
//3
newCap = oldThr;
else { // zero initial threshold signifies using defaults
//4
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//5
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
//6
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//7 如果原有数组不为null,则遍历进行搬迁
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
//如果桶中第一个元素不为空,赋值给e
if ((e = oldTab[j]) != null) {
// 原有桶中元素为null,帮助gc
oldTab[j] = null;
//如果桶中仅有一个元素,计算它在新数组的位置,并进行搬迁
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
//如果头元素是 TreeNode格式,说明该桶已经 树化,则将原有树分化为2个新树插入新的桶中
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else {
//既不是单节点也不是树,说明当前桶是一个链表,则将链表分化为2个链表插入新的桶,比如原来容量为4 ,元素为3、5、7、9 ,在三号桶中,那么分化后 3、7在3号桶, 5、9 在7号桶
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
//将(e.hash & oldCap) == 0的元素放在低位链表中
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
//将(e.hash & oldCap) != 0的元素放在低位链表中
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
//链表分化后 低位链表在新桶中的位置与旧桶一样,高位链表则 j+oldCap
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
- 获取原有数组,原有容量,原有扩容门槛
- 开始更新容量和扩容门槛,
oldCap >0的前提下, 如果原有容量已经达到最大值,则不在进行扩容,仅仅是将 扩容门槛设置为Integer.Max,然后返回原有数组;如果原有容量的2倍 <MAXIMUM_CAPACITY,且 原有容量大于DEFAULT_INITIAL_CAPACITY 16,则 新的扩容门槛为原有2倍 - 若原有扩容门槛 >0, 则将新的容量设置为原有扩容门槛(
newCap = oldThr),仅仅我们使用 非默认构造方法时会走到这里 - 当我们使用默认构造方法时候,原有容量,原有扩容门槛都是0,则初始化容量为默认容量,扩容门槛为 (默认容量 * 默认装载因子)
- 如果新的扩容门槛为0,则将 newThr = (容量 * 装载因子) ,但是不能超过Integer最大值
- 更新扩容门槛和数组
- 下面开始进行元素的搬迁,具体注释已经写在代码里
1.5.3 获取元素get(Object key)
public V get(Object key) {
Node<K,V> e;
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;
//如果数组不为空,且数组长达>0, 且待查找key所在的桶的的第一个元素不为null
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//如果桶中第一个元素的key == 待查找的key的元素,直接返回value
if (first.hash == hash &&
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//反之,first元素的next不为空的
if ((e = first.next) != null) {
//判断 first是不是 TreeNode
if (first instanceof TreeNode)
//是的话,通过 getTreeNode 获取树中的元素
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//反之,通过循环找到链表中的key = 目标key的元素并且返回
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
//如果都没找到,直接返回null
return null;
}
1.5.4 删除元素remove(Object key)
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
//创建新的数组tab并将table赋值给tab。新的数组长度赋值给n,
//如果新的数组不为null,长度>0,且目标key所在的桶的第一个元素不为null,
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e;
K k;
V v;
//如果第一个数组的hash值 ==hash值,key = p.key, key.equas(k),则说明第一个元素就是目标元素
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
//如果该桶的第一个元素有后续元素
else if ((e = p.next) != null) {
//判断是否是树,如果是则getTreeNode 找到目标元素
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
//否则遍历链表来找到目标元素
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
//
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
//如果是TreeNode类型,则通过 removeTreeNode 进行移除
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
//如果是当前桶的第一个元素,直接移除
else if (node == p)
tab[index] = node.next;
//如果是链表,直接跳过目标元素
else
p.next = node.next;
//修改值+1, map的长度-1
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
文中忽略了关于树的操作,后续补充上