源码分析原因
因为面试一致都问,有点烦,所以为了加深印象。
源码版本
JDK 1.8
JDK 1.8 对 HashMap 的修改:
- 添加 红黑二叉树 数据结构, 代替链表结构;
目的:降低冲突寻址复杂度。 - hash 方法 高16位 与 低16位做 ^ (异或)运算;
目的:充分利用hashcode,为了达到更好的散列效果。
静态常量
源码
/**
* The default initial capacity - MUST be a power of two.
* HashMap默认容量为16,必须是二次幂。
* 为什么必须是二次幂?
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
* HashMap最大容量,默认为2的30次方;
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
* 默认负载因子=0.75, 可以在构造器配置该因子。
* 负载因子 = 总键值对数 / 箱子个数
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
* 链表转红黑二叉树的阀值, 当节点冲突 >8 时,转红黑二叉树。
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
* 红黑二叉树转链表的阀值, 当树的节点<6, 转链表。
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
* 在转变成树之前,还会有一次判断,只有键值对数量大于 64 才会发生转换。
* 这是为了避免在哈希表建立初期,多个键值对恰好被放入了同一个链表中而导致不必要的转化
*/
static final int MIN_TREEIFY_CAPACITY = 64;
对象属性
/* ---------------- Fields -------------- */
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
* hash 表的存储引用
*/
transient Node<K,V>[] table;
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
* 缓存 entry 集合
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* The number of key-value mappings contained in this map.
* hash 表的大小(键值对个数)
*/
transient int size;
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
* HashMap被改变的次数
*/
transient int modCount;
/**
* The next size value at which to resize (capacity * load factor).
*HashMap的阈值,用于判断是否需要调整HashMap的容量(threshold = 容量*加载因子)
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
int threshold;
/**
* The load factor for the hash table.
* 加载因子大小
* @serial
*/
final float loadFactor;
主要静态内部类
1. Node<K, V> 节点类
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
* 常用的 基础 Hash 桶节点(链表节点)
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; // 哈希值
final K key; // key 值
V value; // 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;
}
}
2. TreeNode<K, V> 叶子节点类
后面单独写一篇详细介绍TreeNode的,暂时理解为红黑二叉树。
/* ------------------------------------------------------------ */
// Tree bins
/**
* Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
* extends Node) so can be used as extension of either regular or
* linked node.
*/
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; // 红黑标识
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
/**
* Returns root of tree containing this node.
* 根节点方法
*/
final TreeNode<K,V> root() {}
/**
* Ensures that the given root is the first node of its bin.
*/
static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {}
/**
* Finds the node starting at root p with the given hash and key.
* The kc argument caches comparableClassFor(key) upon first use
* comparing keys.
*/
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {}
/**
* Calls find for root node.
*/
final TreeNode<K,V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
/**
* Tie-breaking utility for ordering insertions when equal
* hashCodes and non-comparable. We don't require a total
* order, just a consistent insertion rule to maintain
* equivalence across rebalancings. Tie-breaking further than
* necessary simplifies testing a bit.
*/
static int tieBreakOrder(Object a, Object b) {}
/**
* Forms tree of the nodes linked from this node.
* @return root of tree
*/
final void treeify(Node<K,V>[] tab) {}
/**
* Returns a list of non-TreeNodes replacing those linked from
* this node.
*/
final Node<K,V> untreeify(HashMap<K,V> map) {}
/**
* Tree version of putVal.
*/
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {}
/**
* Removes the given node, that must be present before this call.
* This is messier than typical red-black deletion code because we
* cannot swap the contents of an interior node with a leaf
* successor that is pinned by "next" pointers that are accessible
* independently during traversal. So instead we swap the tree
* linkages. If the current tree appears to have too few nodes,
* the bin is converted back to a plain bin. (The test triggers
* somewhere between 2 and 6 nodes, depending on tree structure).
*/
final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
boolean movable) {}
/**
* Splits nodes in a tree bin into lower and upper tree bins,
* or untreeifies if now too small. Called only from resize;
* see above discussion about split bits and indices.
*
* @param map the map
* @param tab the table for recording bin heads
* @param index the index of the table being split
* @param bit the bit of hash to split on
*/
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {}
/* ------------------------------------------------------------ */
// Red-black tree methods, all adapted from CLR
static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
TreeNode<K,V> p) {}
static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
TreeNode<K,V> p) {}
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
TreeNode<K,V> x) {}
static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
TreeNode<K,V> x) {}
/**
* Recursive invariant check
*/
static <K,V> boolean checkInvariants(TreeNode<K,V> t) {}
}
关键方法
1. hash 方法
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
* 生成 Hash 值生成方法。
* h = key.hashCode(); // 获取 key 的 hash 值
* h >>> 16 ; // 无符号右移 16位
* ^ 异或操作, 相同为0,不同为1.
* 右移异或计算的目的: 让高16位数据参加到散列计算;
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
JDK8 修改1: 对 key的 hash 值做 高低16位做异或运算;
2. put、putVal 方法(Hash Map 插入数据 过程)
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* 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: table 的临时引用
// p: point 节点临时引用
// n: Hash 表大小
// i: index 索引位置
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 1. 初始化空得表
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 2. 根据 hash 值获取数据的索引 i ;
// i = (n - 1) & hash;
// 表大小 & hash 值, 做 & 操作 去掉高位并保证 i < n;
if ((p = tab[i = (n - 1) & hash]) == null)
// 2.1 table 的 i 节点没有值,直接初始化 Node 占用 tab[i];
tab[i] = new Node(hash, key, value, null);
else {
// 2.2 table 的 i 节点有值, 获取旧值。
// e: Node 临时引用,用于返回旧的value;
// k: key 的临时引用
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
// 2.2.1 当旧的节点 p 与新的 key 完全相等,e 引用保存旧节点值;
e = p;
else if (p instanceof TreeNode)
// 2.2.2 当旧的节点 p 是 红黑二叉树,插入新节点到二叉树;
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 2.2.3 链表 hash 冲突处理情况
for (int binCount = 0; ; ++binCount) {
// 2.2.3.1 遍历链表
if ((e = p.next) == null) {
// 2.2.3.1.1 链表末端加入新的节点
p.next = newNode(hash, key, value, null);
// 如果大于TREEIFY_THRESHOLD 二叉树阀值,转成红黑二叉树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 2.2.3.1.2 链表节点与新的节点完全相等, 找到相同节点
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 存在 key 的值,替换新的值,并把原有值返回。
// 因为只是替换原有的value,map容量没增大,modCount不变,直接返回
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
// HashMap 是空方法,HashMap可以忽略这个方法;
// LinedHashMap 需要把节点移到链表的最后;
afterNodeAccess(e);
return oldValue;
}
}
// 新增节点,所以modCount + 1
// size ++ 如果超出了threshold 则 resize 扩容;
++modCount;
if (++size > threshold)
resize();
// HashMap 是空方法,HashMap可以忽略这个方法;
// LinedHashMap 某种情况下,需要把第一个节点移除;
afterNodeInsertion(evict);
return null;
}
3. resize 方法(HashMap 扩容)
/**
* 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 Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
// 缓存旧的容量,旧的阀值;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
// 1. 扩展容量和阀值
if (oldCap > 0) {
// 1.1. 超过最大容量,则取 int 的最大值, 不做结构变更;
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 1.2 没有超过最大容量,则容量翻倍, <<1 相当于 * 2;
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// 1.3 再扩容就超过最大容量,则使用阀值容量;
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// 1.4 初始化默认容量和默认阀值;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 如果新的阀值 = 0, 则使用负载因子 * 新的容量
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
// 刷新阀值
threshold = newThr;
// 初始化新table
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
// 遍历旧table,转移表里键值对;
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
// 节点没法Hash冲突,则直接移到新的节点上;
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);
// 如果低位链表有值,则放回原位置 j
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
// 如果高位链表有值,则放到 j + oldCap 位置
// 为什么到 j + oldCap 呢?因为容量都是2次幂的,扩容也是2次幂;
// 高位的 hash 值肯定是位移 oldCap
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
扩容链表重新分割过程如下
4. tableSizeFor 方法(初始化容量)
该方法保证 HashMap 初始化容量肯定是2次幂;
/**
* Returns a power of two size for the given target capacity.
* 返回 大于等于capacity且最小的二次幂的数。
*/
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;
}
5. get、containKey 方法
放了解 put 方法里面Hash值的散列算法,get方法是指用hash 值读到对应位置的值而已。
还有其他方法都是比较简单的内容了,这里不一一描述。
总结 (不擅长写总结)##
HashMap 主要是 hash 算法 和 红黑二叉树,
hash 算法 是整个数据集根据
hash code 散列到不同的节点,
红黑二叉树则降低冲突访问时,查询复杂度。
遇到的问题:
- Object.hashCode() 怎么实现的?
- 为什么默认初始化大小选16 ?
- TreeNode 详解 (优先级最高)
- TreeNode.prev 的作用是什么?
- modCount 变量的作用是什么?
记录修改次数,用于线程安全问题;