TreeMap的使用
1、简介
TreeMap是红黑二叉树的典型实现。我们打开TreeMap的源码,发现里面有一行核心代码:
root用来存储整个树的根节点。我们继续跟踪Entry(是TreeMap的内部类)的代码:
可以看到里面存储了本身数据、左节点、右节点、父节点、以及节点颜色。
二、使用
1、简单使用
TreeMap会对存入的key进行排序;
TreeMap<Integer, String> treeMap = new TreeMap<>();
treeMap.put(20,"aa");
treeMap.put(30,"bb");
treeMap.put(10,"cc");
for (Integer key : treeMap.keySet()) {
System.out.println(key+"==="+treeMap1.get(key));
}
结果为:
2、key为对象
TreeMap对key的对象,按照给定的compareTo方法进行排序存到TreeMap中。取出来就是有序的;
public class TestTreeMap {
public static void main(String[] args) {
TreeMap<Emp, String> treeMap = new TreeMap<>();
treeMap.put(new Emp(100, "张三", 1000), "张三是个好员工");
treeMap.put(new Emp(200, "李四", 2000), "李四是个好员工");
treeMap.put(new Emp(300, "王五", 3000), "王五是个好员工");
treeMap.put(new Emp(400, "赵六", 2000), "赵六是个好员工");
for (Emp key : treeMap.keySet()) {
System.out.println(key + "====" + treeMap.get(key));
}
}
}
Emp对象:
class Emp implements Comparable<Emp> {
int id;
String name;
double salary;
public Emp(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
@Override
public int compareTo(Emp o) {
//大于1;等于1;小于-1;
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 < o.id) {
return -1;
} else if (this.id == o.id) {
return 0;
}
}
return 0;
}
@Override
public String toString() {
return "Emp{" +
"id=" + id +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
}
结果为: