您的位置:首页 > 其它

TreeSet、TreeMap、HashSet、HashMap底层实现

2015-07-26 09:35 417 查看
TreeMap底层基于红黑树,以下是源代码,先指定一个根节点,若该根节点不存在,则说明TreeMap里面没有元素,将当前准备加入的元素(Entry)加入进去当成根节点。

如果里面已经 存在元素,再判断是否TreeMap是否含有比较器,如果比较器不为空,就按照比较器的比较方法进行比较,如果为空,按照该(key)自己的内部的自然顺序进行

比较,前提是该key是有比较性的,否则,需要将该类继承comparable并重写compareTo方法,使之具有比较性。TreeSet底层就是一个TreeMap,但是Value值为一个虚拟值。因此原理跟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底层则基于Hash表,源代码如下
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
其中调用putVal方法,那么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;
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;
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) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
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;
}
HashMap的排序是无序的,Value可以当成key的附属品,一旦key的值指定,则value就在该位置。指定key的位置的方法,首先,每一个key都有自己的hashCode,根据该hashcode利用hash算法,可以算出该key在当前table的位置,一旦位置确定,判断该位置是否有对应的值,如果有,再通过equals比较,根据返回值,如果返回值为真,则覆盖老的value值,key值不覆盖,但是他们都指向同一个value值,key形成链。如果没有值,则直接将该key存在指定位置。其实HashMap底层就是一个Entry数组。HashMap中的每一个元素都有自己的索引,指定的位置,也就是东西放在该放的地方。找起来就非常方便了。HashSet底层也是基于HashMap实现的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: