类继承层次
底层数据结构
红黑树
TreeMap虽然也是map但是已经不存在hash表的概念
添加元素
重点看一下TreeMap是如何往数据结构中添加元素的:
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
这跟HashMap的put方法截然不同,没有hash的计算,只有key的比较,没有自定义比较器,就使用key的默认比较器。主要看下Entry的结构:
static final class Entry<K,V> implements Map.Entry<K,V> {
K key;
V value;
Entry<K,V> left;
Entry<K,V> right;
Entry<K,V> parent;
boolean color = BLACK;
......
}
结合上面的代码,put方法大意就是把key小的放在父亲节点的left子节点,大的放在right子节点。最主要的方法就是fixAfterInsertion会把Entry构成的二叉树变成一棵红黑树。这里可能有同学会问了,为什么要用红黑树,简单点说是随着元素不断的插入,这个树深度会越来越深而且不平衡。那有同学又可能会问,那为什么不用AVL树,主要是为了读写性能的一个折中选择。
主要方法时间复杂度
containsKey 为 log(n)
get 为 log(n)
put 为 log(n)
remove 为 log(n)
TreeMap隐藏黑科技
一致性哈希
可以把需要做一致性哈希的集合元素计算hashcode作为TreeMap的key即可通过以下方法来获取hash环上的值:
getHigherEntry
getLowerEntry
getFloorEntry
getCeilingEntry
线程安全
fail-fast
线程不安全