0x00.新老HashMap區別
本文使用jdk7(1.7.0_79)與 jdk8(1.8.0_45)進行對比,主要學習數據結構區別
數據結構
jdk7內部數據結構為數組+鏈表,通過key的hash值計算數據所在數組下標,多個key的hash相同或hash計算的數組下標相同,但是key值不同時,往鏈表尾追加Entry。
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
int hash;
}
jdk8內部數據結構為數組+(鏈表 或 紅黑樹),通過key的hash值計算數據所在數組下標,多個key的hash相同或hash計算的數組下標相同,但是key值不同時,檢查節點是否為樹節點,是樹節點則往樹節點添加,如果是普通節點則往鏈表尾追加Entry,當鏈表長度大于8時,則將鏈表轉為紅黑樹。
transient Node<K,V>[] table;
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
}
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;
}
//LinkedHashMap.Entry
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);
}
}
0x01. HashMap.put源碼閱讀
源碼學習,邊看源碼邊加注釋,邊debug,邊理解。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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)
//當HashMap的內部table為空時,觸發resize()
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
//當通過key的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完全相同
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) { //第1個循環是獲取第2個節點了(0->root.next)
//binCount為0時插入的第二個節點
p.next = newNode(hash, key, value, null);
//如果鏈表內的數據已經超過8個則將鏈表轉成紅黑樹
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//binCount等于7時插入的第9個節點
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//檢查tab的長度是否大于等于64,小于則擴容
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
//將Node對象轉為TreeNode
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)
//將TreeNode鏈表轉成紅黑樹
hd.treeify(tab);
}
}
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) {
//root為空時直接第一個元素存入root
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;
if ((ph = p.hash) > h)//優先直接比較hash值
dir = -1;
else if (ph < h)//優先直接比較hash值
dir = 1;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) || //hash值相同則判斷key是否實現Comparable接口
(dir = compareComparables(kc, k, pk)) == 0) //實現了Comparable接口則直接比較
//沒有實現Comparable接口則用System.identityHashCode比較
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;
}
}
}
}
//將root接口放入table的第一個元素
moveRootToFront(tab, root);
}
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) {
//則當前節點為root 直接將顏色設置為黑色
x.red = false;
return x;
}
else if (!xp.red || (xpp = xp.parent) == null)
//當前節點父節點為黑色節點 或者當前節點的父節點時root節點
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);
}
}
}
}
}
}
0x02. 測試代碼
觸發鏈表轉紅黑樹的測試代碼 可直接用來debug
import java.util.HashMap;
/**
* Created by qiyan on 2017/4/9.
*/
public class HashMapTest {
public static void main(String[] args) throws Exception {
//map內的數組容量大于等于64 且 鏈表數量大于8才會進行紅黑樹轉換
HashMap map = new HashMap(64);
for (int i = 0; i <= 8; i++) {
map.put(new HashCodeOneObj(i), i);
}
System.out.println(map);
}
private static class HashCodeOneObj implements Comparable<HashCodeOneObj> {
private int val;
public HashCodeOneObj(int val) {
this.val = val;
}
public int getVal() {
return val;
}
@Override
public int hashCode() {
return 1; //讓所有數據都存入一個桶
}
@Override
public int compareTo(HashCodeOneObj o) {
if (null == o) {
return -1;
}
return Integer.compare(this.getVal(), o.getVal());
}
}
}
鏈表轉紅黑樹過程示意圖:
紅黑樹v2(insert-0-8).png
HashMap中的紅黑樹