TreeMap:键是如何保证排序和唯一的呢?通过二叉树算法,TreeSet的底层就是通过TreeMap的键来完成的
方式一:所以TreeMap保证键的唯一和排序需要让 TreeMap的键的元素所在的类 去实现自然排序Comparable接口
方式二:TreeMap保证键的唯一和排序 需要调用TreeMap的有参构造,传入一个比较器 Comparator
代码演示:
public static void main(String[] args) {
TreeMap<Student, String> tm = new TreeMap<>(new Comparator<Student>() { //用TreeMap的有参构造方法 传入比较器
@Override
public int compare(Student s1, Student s2) {
int num = s1.getName().compareTo(s2.getName()); //按照姓名比较
return num == 0 ? s1.getAge() - s2.getAge() : num;
}
});
tm.put(new Student("张三", 23), "北京");
tm.put(new Student("李四", 13), "上海");
tm.put(new Student("赵六", 43), "深圳");
tm.put(new Student("王五", 33), "广州");
System.out.println(tm);
}
public static void demo1() {
TreeMap<Student, String> tm = new TreeMap<>(); //用TreeMap的无参构造方法创建的对象
tm.put(new Student("张三", 23), "北京"); //Student作为键,必须让Student实现Comparable接口 并且重写CompareTo方法
tm.put(new Student("李四", 13), "上海");
tm.put(new Student("王五", 33), "广州");
tm.put(new Student("赵六", 43), "深圳");
System.out.println(tm);
}
public class Student implements Comparable<Student> { //Student实现了Comparable接口 重写了CompareTo方法
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student o) { // 重写了CompareTo方法
int num = this.age - o.age; //以年龄为主要条件
return num == 0 ? this.name.compareTo(o.name) : num;
}
}
|
|