1.TreeMap数据结构属于红黑树,红黑树是自平衡二叉树
TreeMap节点源码
static final class Entry<K,V> implements Map.Entry<K,V> {
K key; //Entry节点key元素
V value; //Entry节点value元素
Entry<K,V> left = null; //左孩子
Entry<K,V> right = null; //右孩子
Entry<K,V> parent; //父节点
boolean color = BLACK; //标识颜色color
/**
* Make a new cell with given key, value, and parent, and with
* <tt>null</tt> child links, and BLACK color.
*/
Entry(K key, V value, Entry<K,V> parent) {
this.key = key;
this.value = value;
this.parent = parent;
}
2.向TreeMap中添加元素
源码分析
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) { //如果该红黑树根节点为空,插入的元素为根节点
// TBD:
// 5045147: (coll) Adding null to an empty TreeSet should
// throw NullPointerException
//
// compare(key, key); // type check
root = new Entry<K,V>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator; //comparator是构造传入的比较器
if (cpr != null) {
do { //依次从root跟节点查找,查找到该元素的位置
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0) //如果key比对compare返回结果< 0,向左孩子方向走
t = t.left;
else if (cmp > 0) //如果key比对compare返回结果>0,向右孩子方向走
t = t.right;
else
return t.setValue(value); //如果找到了该位置,节点设置到该红黑树的位置上
} while (t != null);
}
else { //如果未传入comparator,直接使用key.compareTo()方法获取比对值
if (key == null)
throw new NullPointerException();
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<K,V>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
3.使用代码实例
3.1未传入比较器
public class TreeMapDemo {
public TreeMapDemo(){
TreeMap<String,Integer> mMap = new TreeMap<String,Integer>();
mMap.put("a", 1);
mMap.put("e", 5);
mMap.put("d", 4);
mMap.put("c", 3);
mMap.put("b", 2);
for(Entry<String, Integer> entry : mMap.entrySet()){
String key = entry.getKey();
Integer val = entry.getValue();
System.out.println("key:" + key + " value:" + val);
}
}
public static void main(String[] args) {
new TreeMapDemo();
}
}
未传入comparator比较器,采用key.compareTo()方法比较,输出结果:
key:a value:1
key:b value:2
key:c value:3
key:d value:4
key:e value:5
3.2传入比较器demo实例
TreeMap<String,Integer> mMap = new TreeMap<String,Integer>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
// TODO Auto-generated method stub
return o2.compareTo(o1); //按照key的逆序
}
});
mMap.put("a", 1);
mMap.put("e", 5);
mMap.put("d", 4);
mMap.put("c", 3);
mMap.put("b", 2);
for(Entry<String, Integer> entry : mMap.entrySet()){
String key = entry.getKey();
Integer val = entry.getValue();
System.out.println("key:" + key + " value:" + val);
}
输出结果:
key:e value:5
key:d value:4
key:c value:3
key:b value:2
key:a value:1