blog

Jdk8-HashMapソースコードの解釈

Java 8では、基礎となるHashMapで使用される構造は、配列、リンクリスト、および赤黒木です。要素数がある値より少ないときは連鎖リスト+配列、要素数がある値より多いときは赤黒木+配列という構造に...

Mar 26, 2020 · 14 min. read
シェア

はじめに

Java 8では、基礎となるHashMapで使用される構造は、配列、連鎖リスト、赤黒木です。要素数がある値より少ない場合は連鎖リスト+配列、要素数がある値より多い場合は赤黒木+配列という構造になります。したがって、Java 8のHashMapを理解するには、まず赤黒木などの概念や性質を理解する必要があります。

この記事はjava 7のHashMapを理解した上で読むことをお勧めします。

赤い木と黒い木の簡単な紹介

HashMapのソースコードを読む前に、赤黒木のいくつかの特徴を理解することが重要です。ここでは、赤黒木の挿入と削除をよりよく理解するために、以下のリンクを開くことをお勧めします。

www.cs.usfca.edu/~galles/vis...

赤黒木の定義

  1. 各ノードは黒か赤
  2. ルート・ノードが黒
  3. 各リーフノードは黒
  4. ノードが赤の場合、その息子は両方とも黒です。
  5. 各ノードについて、そのノードから任意のリーフ・ノードへのすべてのパスは、同じ数のブラック・ノードを含みます。

基本操作

それぞれの新しいノードは、デフォルトの赤で挿入することができ、数値比較のサイズに応じて、位置を決定し、その色を決定することができます。

親ノードが黒の場合、挿入されるノードはその位置を決定するだけでよいのです。

親ノードが赤の場合:

  1. おじさんは空回り+色変わり

=

2. 叔父は赤、親+叔父ノードは黒、祖父ノードは赤

=>

3.おじさんは黒、回転+色変更

赤黒木の挿入操作 - ソースコード

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;
 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() {
 for (TreeNode<K,V> r = this, p;;) {
 if ((p = r.parent) == null)
 return r;
 r = p;
 }
 }
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);
 }
}
Node(int hash, K key, V value, Node<K,V> next) {
 this.hash = hash;
 this.key = key;
 this.value = value;
 this.next = next;
}

挿入操作

static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
 TreeNode<K,V> x) {
 //デフォルトは赤
 x.red = true;
 //xは現在の挿入ノード、xpは親ノード、xppは祖父ノード、xpplは祖父ノードの左ノード、xpprは祖父ノードの右ノードである。
 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)) {
 //祖父ノードの右の子が空でなく、赤である場合、これは上記の基本操作2と同様である。
 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);
 }
 }
 }
 }
 //上のifと似ている
 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);
 }
 }
 }
 }
 }
}

回転操作、左回転を例にとります。

static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
 TreeNode<K,V> p) {
 TreeNode<K,V> r, pp, rl;
 //ここでpは上記で渡されたxp、つまり親ノードを指す
 if (p != null && (r = p.right) != null) {
 if ((rl = p.right = r.left) != null)
 rl.parent = p;
 if ((pp = r.parent = p.parent) == null)
 (root = r).red = false;
 else if (pp.left == p)
 pp.left = r;
 else
 pp.right = r;
 r.left = p;
 p.parent = r;
 }
 return root;
}

左利きの場合 1: 親ノードが空でなく、挿入された右の子ノードがそれ自身の左の子を持つ場合。

if (p != null && (r = p.right) != null) 
if ((rl = p.right = r.left) != null)
 rl.parent = p;
if ((pp = r.parent = p.parent) == null)
 (root = r).red = false;

左利きのケース2:親ノードが空でなく、挿入された右の子ノードが他の子ノードを持たず、親ノードが祖父ノードの左の子である場合。

if (p != null && (r = p.right) != null)
else if (pp.left == p)

左手ケースIII:ケースIIとは逆に、親ノードが空でなく、挿入された右の子ノードが他の子ノードを持たず、親ノードが祖父ノードの右の子である場合。

例として左回りのケース 2 を見てみましょう。balanceInsertionメソッドでは、この時点で個々のノードを再決定し、右回転させます。

if (xp != null) {
 xp.red = false;
 if (xpp != null) {
 xpp.red = true;
 root = rotateRight(root, xpp);
 }
}
//左利きと同じようなもので、ここでは繰り返さない
static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
 TreeNode<K,V> p) {
 TreeNode<K,V> l, pp, lr;
 if (p != null && (l = p.left) != null) {
 if ((lr = p.left = l.right) != null)
 lr.parent = p;
 if ((pp = l.parent = p.parent) == null)
 (root = l).red = false;
 else if (pp.right == p)
 pp.right = l;
 else
 pp.left = l;
 l.right = p;
 p.parent = l;
 }
 return root;
}

putValメソッドのソースコード

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;
 //ポジション・ノードが空なので、Nodeオブジェクトを作成する。
 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))))
 e = p;
 //型がTreeNodeかどうかを判断する
 else if (p instanceof TreeNode)
 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
 //ChainedTable型の下で
 else {
 //連鎖表を繰り返し処理する
 for (int binCount = 0; ; ++binCount) {
 // 
 if ((e = p.next) == null) {
 p.next = newNode(hash, key, value, null);			//値がしきい値より大きいかどうかを判断し、しきい値より大きい場合は赤黒木に変換する。
 if (binCount >= TREEIFY_THRESHOLD - 1)
 treeifyBin(tab, hash);
 break;
 }
 //値が連鎖テーブルに存在するかどうかを判断する
 if (e.hash == hash &&
 ((k = e.key) == key || (key != null && key.equals(k))))
 break;
 p = e;
 }
 }
 // 
 if (e != null) {
 V oldValue = e.value;
 if (!onlyIfAbsent || oldValue == null)
 e.value = value;
 afterNodeAccess(e);
 return oldValue;
 }
 }
 //修正
 ++modCount;
 //展開するかどうかの判断
 if (++size > threshold)
 resize();
 // 
 afterNodeInsertion(evict);
 return null;
}

treeifyBinメソッドのソースコード

final void treeifyBin(Node<K,V>[] tab, int hash) {
 int n, index; Node<K,V> e;
 //配列が空であり、配列のサイズが64未満であるかどうか、それはツリーではなく、拡張に行く、拡張した後、クエリの効率を向上させるように、チェーンテーブルの長さが短くなる可能性があるため 
 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 {
 //TreeNodeノードを返すのと等価である。
 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)
 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) {
 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)
 dir = -1;
 else if (ph < h)
 dir = 1;
 else if ((kc == null &&
 //もしnullの戻り値に実装されていない場合、Comparableインターフェイスの実装が、実行時の戻り値の型の実装がkかどうかを判断する
 // xがkc型の場合、kを返す。.compareTo(x)xがnullであるか、型がkcでない場合、0を返す。
 (kc = comparableClassFor(k)) == null) ||
 (dir = compareComparables(kc, k, pk)) == 0)
 //まず、2つのオブジェクトのクラス名を比較する。クラス名は文字列オブジェクトであり、文字列比較ルールに従っている。 2つのオブジェクトが同じ型であれば、ローカル・メソッドを呼び出して2つのオブジェクトのhashCode値を生成し、比較する。,k<=pk,は-1を返す。
 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);
}
//非フォーカス、ここでは繰り返さない
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];
 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);
 }
}

resize

final Node<K,V>[] resize() {
 Node<K,V>[] oldTab = table;
 int oldCap = (oldTab == null) ? 0 : oldTab.length;
 int oldThr = threshold;
 int newCap, newThr = 0;
 if (oldCap > 0) {
 if (oldCap >= MAXIMUM_CAPACITY) {
 threshold = Integer.MAX_VALUE;
 return oldTab;
 }
 //MAXIMUM_CAPACITY:1<<30
 //DEFAULT_INITIAL_CAPACITY:16
 else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
 oldCap >= DEFAULT_INITIAL_CAPACITY)
 newThr = oldThr << 1; 
 }
 else if (oldThr > 0) 
 newCap = oldThr;
 //oldCap==0
 else { 
 newCap = DEFAULT_INITIAL_CAPACITY;
 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
 }
 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"})
 Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
 table = newTab;
 //以上が初期化処理である。
 if (oldTab != null) {
 for (int j = 0; j < oldCap; ++j) {
 Node<K,V> e;
 if ((e = oldTab[j]) != null) {
 oldTab[j] = null;
 //eの次のノードが空、つまり現在のoldTabのとき[j]次のノードが空の場合、新しい配列の添え字を直接
 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 {
 Node<K,V> loHead = null, loTail = null;
 Node<K,V> hiHead = null, hiTail = null;
 Node<K,V> next;
 //Java 7HashMapの展開操作に似ている、つまり、ノードの下の連鎖表の下の配列添え字は、現在の配列添え字のまま、または現在の添え字のどちらかで展開される+old.length
 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);
 if (loTail != null) {
 loTail.next = null;
 newTab[j] = loHead;
 }
 if (hiTail != null) {
 hiTail.next = null;
 newTab[j + oldCap] = hiHead;
 }
 }
 }
 }
 }
 return newTab;
}
//双方向リンクリストを使って、赤黒木を2つの小さなリンクリストに分割しようとしている。
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
 TreeNode<K,V> b = this;
 TreeNode<K,V> loHead = null, loTail = null;
 TreeNode<K,V> hiHead = null, hiTail = null;
 int lc = 0, hc = 0;
 //resizeでの操作と同様に、2つのリンクリストに分割する。 
 for (TreeNode<K,V> e = b, next; e != null; e = next) {
 next = (TreeNode<K,V>)e.next;
 e.next = null;
 if ((e.hash & bit) == 0) {
 if ((e.prev = loTail) == null)
 loHead = e;
 else
 loTail.next = e;
 loTail = e;
 ++lc;
 }
 else {
 if ((e.prev = hiTail) == null)
 hiHead = e;
 else
 hiTail.next = e;
 hiTail = e;
 ++hc;
 }
 }
 if (loHead != null) {
 //連鎖表の低レベルが6未満の場合、一方向性連鎖表に変換される。
 if (lc <= UNTREEIFY_THRESHOLD)
 tab[index] = loHead.untreeify(map);
 //チェーンテーブルの高レベルが存在しない場合、それはツリーの直接転送に等しい、この時点で、まだツリーを維持する
 else {
 tab[index] = loHead;
 if (hiHead != null)
 loHead.treeify(tab);
 }
 }
 //上記に似ている
 if (hiHead != null) {
 if (hc <= UNTREEIFY_THRESHOLD)
 tab[index + bit] = hiHead.untreeify(map);
 else {
 tab[index + bit] = hiHead;
 if (loHead != null)
 hiHead.treeify(tab);
 }
 }
}

get

そのままソースコードを提供

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;
 if ((tab = table) != null && (n = tab.length) > 0 &&
 (first = tab[(n - 1) & hash]) != null) {
 if (first.hash == hash && 
 ((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;
}
final TreeNode<K,V> getTreeNode(int h, Object k) {
 return ((parent != null) ? root() : this).find(h, k, null);
}
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
 TreeNode<K,V> p = this;
 do {
 int ph, dir; K pk;
 TreeNode<K,V> pl = p.left, pr = p.right, q;
 if ((ph = p.hash) > h)
 p = pl;
 else if (ph < h)
 p = pr;
 else if ((pk = p.key) == k || (k != null && k.equals(pk)))
 return p;
 else if (pl == null)
 p = pr;
 else if (pr == null)
 p = pl;
 else if ((kc != null ||
 (kc = comparableClassFor(k)) != null) &&
 (dir = compareComparables(kc, k, pk)) != 0)
 p = (dir < 0) ? pl : pr;
 else if ((q = pr.find(h, k, kc)) != null)
 return q;
 else
 p = pl;
 } while (p != null);
 return null;
}

remove

public final void remove() {
 Node<K,V> p = current;
 if (p == null)
 throw new IllegalStateException();
 if (modCount != expectedModCount)
 throw new ConcurrentModificationException();
 current = null;
 K key = p.key;
 removeNode(hash(key), key, null, false, false);
 expectedModCount = modCount;
}
//連鎖表か赤黒木かを判断し、連鎖表であれば、まず取得し、次に削除する。.8matchメソッドで、削除するキーと値を照合し、ツリーであればremoveTreeNodeメソッドを実行する。
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;
 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;
 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);
 }
 }
 if (node != null && (!matchValue || (v = node.value) == value ||
 (value != null && value.equals(v)))) {
 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;
 ++modCount;
 --size;
 afterNodeRemoval(node);
 return node;
 }
 }
 return null;
}
final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
 boolean movable) {
 int n;
 if (tab == null || (n = tab.length) == 0)
 return;
 int index = (n - 1) & hash;
 TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
 TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
 if (pred == null)
 tab[index] = first = succ;
 else
 pred.next = succ;
 if (succ != null)
 succ.prev = pred;
 if (first == null)
 return;
 if (root.parent != null)
 root = root.root();
 if (root == null
 || (movable
 && (root.right == null
 || (rl = root.left) == null
 || rl.left == null))) {
 tab[index] = first.untreeify(map); 
 return;
 }
 TreeNode<K,V> p = this, pl = left, pr = right, replacement;
 if (pl != null && pr != null) {
 TreeNode<K,V> s = pr, sl;
 while ((sl = s.left) != null) 
 s = sl;
 boolean c = s.red; s.red = p.red; p.red = c; 
 TreeNode<K,V> sr = s.right;
 TreeNode<K,V> pp = p.parent;
 if (s == pr) { 
 p.parent = s;
 s.right = p;
 }
 else {
 TreeNode<K,V> sp = s.parent;
 if ((p.parent = sp) != null) {
 if (s == sp.left)
 sp.left = p;
 else
 sp.right = p;
 }
 if ((s.right = pr) != null)
 pr.parent = s;
 }
 p.left = null;
 if ((p.right = sr) != null)
 sr.parent = p;
 if ((s.left = pl) != null)
 pl.parent = s;
 if ((s.parent = pp) == null)
 root = s;
 else if (p == pp.left)
 pp.left = s;
 else
 pp.right = s;
 if (sr != null)
 replacement = sr;
 else
 replacement = p;
 }
 else if (pl != null)
 replacement = pl;
 else if (pr != null)
 replacement = pr;
 else
 replacement = p;
 if (replacement != p) {
 TreeNode<K,V> pp = replacement.parent = p.parent;
 if (pp == null)
 root = replacement;
 else if (p == pp.left)
 pp.left = replacement;
 else
 pp.right = replacement;
 p.left = p.right = p.parent = null;
 }
 TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);
 if (replacement == p) { 
 TreeNode<K,V> pp = p.parent;
 p.parent = null;
 if (pp != null) {
 if (p == pp.left)
 pp.left = null;
 else if (p == pp.right)
 pp.right = null;
 }
 }
 if (movable)
 moveRootToFront(tab, r);
}

TreeNodeタイプが削除された場合、以下の条件のいずれかを満たす必要があるときは、赤黒ツリーを連鎖テーブルに変換することが可能であることに注意してください。

root == null
movable
root.right == null
(rl = root.left) == null
rl.left == null

赤黒ツリーの削除操作は複雑すぎるので、私のコーディングスキルが向上したら、またこの穴を埋めに行きます

Read next

JavaScriptの基本概念_赤い表紙_1

"\n\n"失敗から学んだ "本を2ヶ月噛みます。\n" 町の赤本\n"\n\n基本コンセプト\n"\n「1995年、「主な目的は、現在のサーバー言語が担っていたテストのいくつかに対処すること」であった時代に生まれました。

Mar 26, 2020 · 6 min read