Java8-HashMap实现原理<一>
2018-08-22 本文已影响182人
BlackJava
HashMap 是用于存储key,value 键值对信息数据的,key 和 Value 都可以为NULL。
Java7 HashMap 采用的是 数组+链表 形式存储数据,例如的:
而 Java8中 采取的是 数组 + 链表 + 红黑树,例如:
Java8-HashMap数据结构
引入红黑树的原因在于:
当HashMap中hash碰撞比较厉害的时候,查找链表数据就会变成单纯的链表查询,这个查询效率O(n),而引入红黑树的结构可以使查询效率优化为O(logn)。
红黑树的特点:
(1)每个节点或者是黑色,或者是红色。
(2)根节点是黑色。
(3)每个叶子节点(NIL节点)是黑色。 [注意:这里叶子节点,是指为空(NIL或NULL)的叶子节点!]
(4)如果一个节点是红色的,则它的子节点必须是黑色的。
(5)从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑节点。
下面我们来具体分析一下他的实现原理,内容会比较细致一点:
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.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
这里我们需要解释一下了:
1.如果保存数据中 key == null, hash值默认为 0;
2.取的是实体的hashcode 值进行运算
3.运算规则^(异或),hashcode值 向右移16位 然后 和 hashcode 进行异或算法,这样就确定了数组的下标位置,我们来看一下
Tab的 index下标确定规则采用的是&(按位与):都为1 才为1
tab[(n - 1) & hash])
插入实现:
/**
* 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) {
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))))
// 判断key 是否相同(hash值,物理地址,equal),相同则更新对应的值
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) {
// 如果节点的 next 为空,插入新的数据
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
// 当链表的节点数量 大于 8个时候,整个链表就会转化成红黑树
treeifyBin(tab, hash);
break;
}
// 找到 key 相同的节点信息
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 如果是 插入 e是为空的,如果不为空,则是找到相同的节点信息了,根据配置替换数据
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 如果map的整体大小超过了将要 扩容的大小,则使用扩容因子进行扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
我可以发现,
1.相对于Java7而言新增了 红黑树节点查找插入的逻辑
2.链表转化成红黑树时,只有当链表的节点个数超过了 8 才会转化成红黑树转化方法为treeifyBin
treeifyBin实现——将链表转化成LinkedHashMap
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
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 {
// 将所有的Node链表 转化成 LinkedHashMap结构
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)
// 从根节点开始对 LinkedHashMap结构进行 红黑树转化
hd.treeify(tab);
}
}
// For treeifyBin
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}
treeify实现——将LinkedHashMap 转化成 二叉树
/**
* Forms tree of the nodes linked from this node.
* @return root of tree
*/
final void treeify(Node<K,V>[] tab) {
TreeNode<K,V> root = null;
for (TreeNode<K,V> x = this, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next;
x.left = x.right = null;
if (root == null) {
// 设置根节点信息,根节点为 黑色
x.parent = null;
x.red = false;
root = x;
}
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
for (TreeNode<K,V> p = root;;) {
int dir, ph;
K pk = p.key;
// 二叉树中 左右分支确认 在于 dir 的 正负,<= 0 在左分支, > 0 在右分支
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
// 如果hash值相等,则比较名字的前后,如果实现了Comparable 则使用 Comparable 进行比较
dir = tieBreakOrder(k, pk);
TreeNode<K,V> xp = p;
// 这里就开始转化成 二叉树了 ,确定左右分支的值
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
// 对二叉树 进行平衡处理,左旋,或者 右旋 等等操作
root = balanceInsertion(root, x);
break;
}
}
}
}
moveRootToFront(tab, root);
}
balanceInsertion实现——将二叉树 转化成 红黑树(这个部分有点难具体可以看一下红黑树实现原理)
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root, TreeNode<K,V> x) {
x.red = true;
for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
if ((xp = x.parent) == null) {
// 如果一层树结构,设置根节点为黑色
x.red = false;
return x;
}
else if (!xp.red || (xpp = xp.parent) == null)
// 只有两层树结构 并且 根节点为 黑色,则满足红黑树要求
return root;
if (xp == (xppl = xpp.left)) {
// 有三层树结构 时,左分支判断
if ((xppr = xpp.right) != null && xppr.red) {
xppr.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.right) {
// 左旋
root = rotateLeft(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
// 右旋
root = rotateRight(root, xpp);
}
}
}
}
else {
// 有三层树结构 时,右分支判断
if (xppl != null && xppl.red) {
xppl.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.left) {
// 右旋
root = rotateRight(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
// 左旋
root = rotateLeft(root, xpp);
}
}
}
}
}
}
我们直接上结果,以上就完成了平衡二叉B树转换,还有一个函数moveRootToFront()
moveRootToFront实现——将LinkedHashMap中的root节点与二叉树的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) {
int n;
if (root != null && tab != null && (n = tab.length) > 0) {
int index = (n - 1) & root.hash;
TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
// 将LinkedHashMap中的root节点prev,next 与二叉树的root节点prev,next替换
if (root != first) {
Node<K,V> rn;
tab[index] = root;
TreeNode<K,V> rp = root.prev;
if ((rn = root.next) != null)
((TreeNode<K,V>)rn).prev = rp;
if (rp != null)
rp.next = rn;
if (first != null)
first.prev = root;
root.next = first;
root.prev = null;
}
assert checkInvariants(root);
}
}
好了,这就是链表转 红黑树实现了,现在还剩下一个部分,已经是红黑树了,再插入节点信息,如何插入?
putTreeVal实现
/**
* Tree version of putVal.
*/
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K,V> root = (parent != null) ? root() : this;
// 从根节点开始,往下遍历
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
// 计算 插入值与当前节点的 hash比较 dir值
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
// 如果当前节点的 dir 对应的叶子节点 为空,则插入,如果有值,从dir 值对应的分支循环查找
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node<K,V> xpn = xp.next;
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
// 插入对应的 节点,并设置对应的信息
if (dir <= 0)
xp.left = x;
else
xp.right = x;
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
// 这里做了两步,首先平衡二叉树,然后设置LinkedHashMap 的root信息
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
以上部分就是put的全部实现了。