TreeMap的使用和底层实现
TreeMap的实现
TreeMap是红黑二叉树的典型实现。打开TreeMap的源码,发现里面有一行核心代码:
private transient Entry<K,V> root = null;
root用来存储整个树的根节点。我们继续跟踪Entry(是TreeMap的内部类)的代码
可以看到里面存储了本身数据、左节点、右节点、父节点、以及节点颜色。 TreeMap的put()/remove()方法大量使用了红黑树的理论。
TreeMap和HashMap实现了同样的接口Map,因此,用法对于调用者来说没有区别。HashMap效率高于TreeMap;在需要排序的Map时才选用TreeMap。
TreeMap的使用
public class TestTreeMap {
public static void main(String[] args) {
Map<Integer, String> treemap1 = new TreeMap();
treemap1.put(1, "aa");
treemap1.put(99, "vv");
treemap1.put(50, "cc");
for(Integer key:treemap1.keySet()) {
System.out.println(key+"----"+treemap1.get(key));
}
Map<Emp,String> tmap2 = new TreeMap();
Emp e1 = new Emp(17,"阿狸",50000);
Emp e2 = new Emp(19,"阿卡丽",21000);
Emp e3 = new Emp(21,"艾瑞利亚",35000);
tmap2.put(e1, "阿狸温柔又美丽");
tmap2.put(e2, "阿卡丽苗条又灵活");
tmap2.put(e3, "刀妹腿长腰又细");
for(Emp key:tmap2.keySet()) {
System.out.println(key+"-----"+tmap2.get(key));
}
}
}
class Emp implements Comparable<Emp>{
int id;
String name;
int salary;
public Emp(int id, String name, int salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
@Override
public int compareTo(Emp o) {
if(this.salary>o.salary) {
return -1;
}else if(this.salary<o.salary) {
return 1;
}else {
if(this.id>o.id) {
return 1;
}else if(this.id<id){
return -1;
}
}
return 0;
}
public String toString() {
return "id:"+id+"\t"+"name:"+name+"\t"+"salary:"+salary;
}
}
效果