/**
*
* 1.创建集合对象TreeMap<String,String> map = new TreeMap<String ,String>();
*
* private final Comparator<? super K> comparator;//外部比较器
private transient Entry<K,V> root = null;//红黑树根节点的引用
* public TreeMap() {
comparator = null;//没有指定外部比较器
}
*
*
* 2.添加键值对 map.put("cn", "China");
*
* 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);
}
//如果没有找到指定的关键字,新创建一个节点,并加入到指定的位置,节点数量+1
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;
}
*
* 红黑树中节点的结构
* static final class Entry<K,V> implements Map.Entry<K,V> {
K key; //key cn
V value; //value China
Entry<K,V> left = null; //指向左孩子 null
Entry<K,V> right = null;//指向右孩子
Entry<K,V> parent; //指向父结点
boolean color = BLACK;//该节点的颜色
}
*
* 3.根据key或者值map.get("cn")
*
* final Entry<K,V> getEntry(Object key) {
// Offload comparator-based version for sake of performance
//如果有外部比较器Comparator,优先使用外部比较器
if (comparator != null)
return getEntryUsingComparator(key);
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
//如果没有外部比较器,就使用内部比较器Comparable
Comparable<? super K> k = (Comparable<? super K>) key;
Entry<K,V> p = root;
while (p != null) {
int cmp = k.compareTo(p.key);
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
//找到了,就返回
return p;
}
//如果没有找到,返回null
return null;
}
*
*
* @author Administrator
*
*/
public class TestTreeMap {
public static void main(String[] args) {
TreeMap<String,String> map = new TreeMap<String ,String>();
map.put("cn", "China");
map.put("us", "the United States");
map.put("us", "America");
System.out.println(map.get("cn"));
}
}
TreeMap储值原理
最新推荐文章于 2022-11-27 16:27:56 发布