查看实现,它看起来像一棵二叉树。更具体地说,下面的评论表明它是一棵红黑树:
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;
...
}
关于处理相等的哈希码,这在 Javadoc 中有说明:
树箱(即元素都是 TreeNodes 的箱)是
主要按 hashCode 排序,但在平局的情况下,如果两个
元素是相同的“class C implements Comparable<C>”,
type 然后他们的 compareTo 方法用于排序。
据说HashMap 中使用的TreeNodes 的结构类似于TreeMap。
您可以在此处查看搜索包含所需密钥的TreeNode 的实现:
/**
* 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) {
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;
}
如您所见,这类似于标准的二叉搜索树搜索。首先,他们搜索具有与搜索键相同的hashCode 的TreeNode(因为HashMap 的单个桶可能包含具有不同hashCodes 的条目)。然后它继续直到找到具有等于所需密钥的密钥的TreeNode。如果键的类实现Comparable,则辅助搜索使用compareTo。否则,将执行更详尽的搜索。