//返回找到的value,找不到返回null public V get(Objectkey) { Entry<K,V> p = getEntry(key); return (p==null ? null : p.value); }
final Entry<K,V> getEntry(Objectkey) { // Offload comparator-based version for sake of performance if (comparator != null) //如果comparator不为null,调用这个方法 return getEntryUsingComparator(key); if (key == null) thrownew NullPointerException(); @SuppressWarnings("unchecked") Comparable<? super K> k = (Comparable<? super K>) key; Entry<K,V> p = root; //不然就是使用compareTo()方法 //从红黑树中找到对应的值,返回出去 while (p != null) { int cmp = k.compareTo(p.key); if (cmp < 0) p = p.left; elseif (cmp > 0) p = p.right; else return p; } returnnull; }
final Entry<K,V> getEntryUsingComparator(Objectkey) { @SuppressWarnings("unchecked") K k = (K) key; Comparator<? super K> cpr = comparator; if (cpr != null) { Entry<K,V> p = root; while (p != null) { //调用的是Comparator自己实现的方法来获取对应的位置,总体逻辑和外面没啥区别 int cmp = cpr.compare(k, p.key); if (cmp < 0) p = p.left; elseif (cmp > 0) p = p.right; else return p; } } returnnull; }
remove
1 2 3 4 5 6 7 8 9 10
public V remove(Objectkey) { Entry<K,V> p = getEntry(key); if (p == null) returnnull;
V oldValue = p.value; //删除节点并且平衡红黑树 deleteEntry(p); return oldValue; }