1. 几个重要的常量
类型 | 常量 | 解释 |
---|---|---|
int | DEFAULT_INITIAL_CAPACITY | 默认初始table大小(16) |
int | MAXIMUM_CAPACITY | 最大长度(1 << 30,2的30次方) |
int | DEFAULT_LOAD_FACTOR | 缺省负载因子大小(0.75) |
int | THREEIFY_THRESHOLD | 树化阈值(8) |
int | UNTREEIFY_THRESHOLD | 树降级为链表的阈值(6) |
int | MIN_TREEIFY_CAPACITY | 树化的另一个参数,当哈希表中所有元素的个数超过64才会树化(64) |
2. 几个重要属性
类型 | 属性名 | 解释 |
---|---|---|
Node<K, V>[] | table | 哈希表,在第一次put数据时初始化 |
int | size | 当前table中元素个数 |
int | modCount | 当前table结构修改次数(插入元素,减去元素数据结构修改,替换不属于结构修改) |
int | threshold | 扩容阈值,当table中的元素个数超过此阈值,触发扩容 |
float | loadFactor | 负载因子,threshold = capacity * loadFactor(扩容阈值 = 哈希表大小 * 负载因子) |
3. 几个重要方法
3.1 双参构造方法
public HashMap(int initialCapacity, float loadFactor) {
// 做了一些校验
// capacity 必须大于 0
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
// capacity 若大于允许的最大值,则调整capacity为允许的最大值
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
// loadFactor 必须大于 0
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
// 给负载因子赋值
this.loadFactor = loadFactor;
// 得到一个大于 capacity 且最接近 capacity 的2的次方的数字赋值给扩容阈值threshold
// 详细见下方解析
this.threshold = tableSizeFor(initialCapacity);
}
/**
* 返回一个大于等于当前cap且最接近cap的一个数字,此数字一定是一个2的次方数(16,32,64,...)
*/
static final int tableSizeFor(int cap) {
int n = cap - 1; // 假设 cap = 10,n = 9(二进制 1001)
n |= n >>> 1; // 1001 | 0100(1001 右移1位) => 1101
n |= n >>> 2; // 1101 | 0011(1101 右移2位) => 1111
n |= n >>> 4; // 1111 | 0000(1111 右移4位) => 1111
n |= n >>> 8; // 1111 | 0000(1111 右移8位) => 1111
n |= n >>> 16; // 1111 | 0000(1111 右移16位)=> 1111 = 十进制 15
// n = 15,大于0 且 小于 MAXIMUM_CAPACITY,返回 15 + 1 = 16
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
注意:若没有 n = cap - 1 这一步,则最终得到的值将会大1倍(本来仅需要16,却返回32)
3.2 put 方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
使用 putVal 方法和 hash 方法实现了 put 操作
1. hash 方法(哈希扰动)
目的:让 key 的 hash 值的高 16 位也参与路由运算(为了减少 hash 碰撞)
static final int hash(Object key) {
int h;
// 若 key == null,则返回 0(把数据放在 table 的第 0 位置)
// 若 key != null,得到 key 的 hashCode,让此 hashCode 与 它无符号右移 16 位的数进行异或运算
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
例子:
假设 h = key.hashCode() = 0010 0101 1010 1100 0011 1111 0010 1110
h 无符号右移16位 = 0000 0000 0000 0000 0010 0101 1010 1100
异或运算后 = 0010 0101 1010 1100 0001 1010 1000 0010
【注】异或运算:相同返回 0,不同返回 1
2. putVal 方法
/**
* Implements Map.put and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
// tab:引用当前hashMap的散列表
// p:当前散列表元素
// n:散列表数组长度
// i:路由寻址结果
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 如果 table 没有初始化过,则在第一次 putVal 时,初始化 HashMap 中最占用内存的 table 散列表
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// (n - 1) & hash => 寻址算法:找到要插入的位置,并将其赋值给 i
// tab[i = (n - 1) & hash] => 寻址算法找到哈希表的的元素,并赋值给 p
// 若 p == null,说明没有任何碰撞,可直接插入此位置
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 寻址的位置有数据了
else {
// e:不为 null 的话,找到一个与当前要插入的 key - value 一致的 key 的元素
// k:临时的一个 key
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 {
// 链表的情况,且链表的头元素与要插入的 key 不一致
for (int binCount = 0; ; ++binCount) {
// 说明已经循环链表的最后一个元素了,且没有找到一个与插入元素的 key 一致的节点
if ((e = p.next) == null) {
// 在链表尾部插入一个新的 node 元素
p.next = newNode(hash, key, value, null);
// 链表长度达到树化标准,需要进行树化操作
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 说明找到了一个相同 key 的 node 元素,需要进行替换
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
// p作为指针向后移
p = e;
}
}
// 说明找到了一个与【要插入的元素】的 key 完全一致的元素,需要进行替换
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
// 散列表结构修改次数 + 1(插入/删除属于修改结构,替换不属于)
++modCount;
// 插入新元素,size 自增,若 size 大于扩容阈值,则扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
putVal 方法流程图
3.3 resize 方法
目的:为了解决哈希冲突导致链化影响查询效率的问题
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
final HashMap.Node<K,V>[] resize() {
// oldTab:引用扩容之前的哈希表
HashMap.Node<K,V>[] oldTab = table;
// oldCap:扩容之前 table 数组大小
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// oldThr:扩容之前的扩容阈值,即触发本次扩容的阈值
int oldThr = threshold;
// newCap:扩容之后 table 数组的大小
// newThr:扩容之后,下次触发扩容的阈值
int newCap, newThr = 0;
// HashMap 已被初始化过,是一个正常扩容
if (oldCap > 0) {
// 扩容前的 table 数组大小已经达到允许的最大值(这种情况比较少)
// 则不进行扩容,且设置扩容条件为 int 最大值
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 正常扩容:
// oldCap 左移1位实现数据翻倍,赋值给 newCap,newCap 小于允许的最大值
// 且扩容前的阈值 >= 16
// 则【下次扩容的阈值】 = 【当前阈值翻倍】
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// oldCap == 0,即 HapsMap 没有被初始化过,且 oldThr > 0
// 注:在如下 3 种情况下创建 HashMap 时 oldThr > 0
// 1. new HashMap(initCap, loadFactor);
// 2. new HashMap(initCap);
// 3. new HashMap(map); 且 map 有数据
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// oldCap == 0,即 HashMap 没有被初始化过,且 oldThr == 0
// 注:在 new HashMap(); 时,oldThr == 0
else { // zero initial threshold signifies using defaults
// 扩容后 table 数组大小(默认) = 16
newCap = DEFAULT_INITIAL_CAPACITY;
// 下次扩容阈值(默认) = 0.75 * 16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 通过 newCap 和 loadFactor 计算出一个 newThr
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"})
HashMap.Node<K,V>[] newTab = (HashMap.Node<K,V>[])new HashMap.Node[newCap];
table = newTab;
// 本次扩容之前 table 不为 null
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
// 当前 node 节点
HashMap.Node<K,V> e;
// 说明当前桶位有数据,但是数据具体是【单个数据】,还是【链表】,还是【红黑树】并不知道
if ((e = oldTab[j]) != null) {
// 方便 JVM GC 回收内存
oldTab[j] = null;
// 【单个数据】当前桶位只有 1 个元素,没有碰撞,直接计算出当前元素应存放的位置并存放
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
// 【红黑树】当前节点已经树化
else if (e instanceof HashMap.TreeNode)
((HashMap.TreeNode<K,V>)e).split(this, newTab, j, oldCap);
// 【链表】当前节点已经形成链表
else { // preserve order
// 低位链表:存放扩容之后的数组下标位置与【当前数组下标位置】一致的元素
HashMap.Node<K,V> loHead = null, loTail = null;
// 高位链表:存放扩容之后的数组下标位置为【当前数组下标位置】+ 【扩容之前的数组长度】的元素
HashMap.Node<K,V> hiHead = null, hiTail = null;
// 当前元素的下个元素
HashMap.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);
// 把低位链表的最后一个元素的 next 置为 null
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
// 把高位链表的最后一个元素的 next 置为 null
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
注意:关于高位链表与低位链表
假设扩容前 table 数组大小为 16,扩容后为 32,那么:
- 扩容前,在下标 15 的链表中的数据的 key 的哈希值的后 5 位只有可能是01111和11111
- 扩容后,这些数据只有可能对应到 15(01111)或 31(11111)两个位置,15 位置对应低位链表,31 位置对应高位链表。
resize 方法流程图(计算扩容参数部分)
3.4 get 方法
public V get(Object key) {
HashMap.Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
1. hash 方法(哈希扰动)
同 put 方法的 hash 方法,详见上文
2. getNode 方法
final Node<K,V> getNode(int hash, Object key) {
// tab:引用当前 hashMap 的散列表
// first:桶位中的头元素
// e:临时 node 元素
// n:table 数组长度
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) {
// 定位出来的桶位元素,即为我们需要 get 的元素
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;
}
3.5 remove 方法
/**
* Implements Map.remove and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to match if matchValue, else ignored
* @param matchValue if true only remove if value is equal
* @param movable if false do not move other nodes while removing
* @return the node, or null if none
*/
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
// tab:引用当前 HansMap 中的散列表
// p:当前 node 元素
// n:table 数组长度
// index:寻址结果
Node<K,V>[] tab; Node<K,V> p; int n, index;
// 路由的桶位是有数据的,需要进行查找操作,并删除
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
// node:查找到的结果
// e:当前 node 的 next
Node<K,V> node = null, e; K k; V v;
// 当前桶位中的元素即为要删除的元素
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
// 当前桶位可能是【链表】可能是【红黑树】
else if ((e = p.next) != null) {
// 当前桶位是否为【红黑树】
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);
}
}
// 判断 node 不为空,说明按照 key 查找到要删除的数据了
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
// node 是树节点,要进行树节点移除
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
// 桶位元素即为查找结果,将该元素的下一个元素放置桶位中
else if (node == p)
tab[index] = node.next;
// 删除 node 元素
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}