1、容器TreeMap,默认根据Key对象中某个属性的从小到大排列元素。
(1)如下代码示例,Key是整型数字,所以按照其从小到大的顺序排列
public class TestTreeMap {
public static void main(String[] args){
TreeMap<Integer,String> treeMap = new TreeMap<>();
treeMap.put(100,"1号");
treeMap.put(102,"2号");
treeMap.put(101,"3号");
System.out.println(treeMap);
}
}
/*output:
{100=1号, 101=3号, 102=2号}
*/
(2)当Key是自定义类的实例时,自定义类要实现Comparable<T>接口,重写compareTo(T)方法;
主要工作就是在自定义类中定义一个可以比较的属性,同时实现比较方法compareTo:
public class TestTreeMap {
public static void main(String[] args){
Person person1 = new Person(100,"张",5000);
Person person2 = new Person(102,"王",6000);
Person person3 = new Person(101,"李",7000);
TreeMap<Person,String> treeMap1 = new TreeMap<>();
treeMap1.put(person1,"一班");
treeMap1.put(person2,"二班");
treeMap1.put(person3,"三班"); Set<Map.Entry<Person,String>> set = treeMap1.entrySet();
for (Map.Entry<Person, String> entry : set) {
System.out.print(entry.getKey().id+"="+ entry.getValue()+'\t');
}
}
}
class Person implements Comparable<Person>{
public int id;
public String name;
public int salary; public Person(int id, String name, int salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public Person(){ }
public int compareTo(Person e){
if (this.id > e.id){
return 1;
}else if(this.id < e.id){
return -1;
}else{
return 0;
}
}
}
/*output:
100=一班 101=三班 102=二班
*/
2、TreeSet和TreeMap类似,因为TreeSet的底层也是TreeMap实现,TreeSet存储的元素,底层是存放在TreeMap的Key位置
即TreeSet存储自定义类的对象时,也需要将自定义类实现Comparable<T>接口,此处分析省略