JAVA中TreeMap类两种常用构造方法
JAVA的JDK文档中,TreeMap类有四种构造方法,下面我们讲述最常见的两类:
第一种:
第一种构造方法,创建对象时如果没有传入比较器,那么就按元素的自然顺序排序;
这里,元素的"自然顺序"是什么?其实答案就是,比较对象要实现 Comparable 接口, 自然比较的规则就是对象在实现Comparable 接口中,重写CompareTo()函数时定义的规则;
我们第一个Student类,实现Comparable接口,并重写CompareTo方法
public class Student implements Comparable<Student> { //public class Student{ private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public int compareTo(Student s1) { int cmp = name.compareTo(s1.name); cmp = cmp != 0 ? cmp : age - s1.age; return cmp; } }
在定义时如下使用:
Student s1 = new Student("Allen", 20); Student s2 = new Student("Beyonce", 20); Student s3 = new Student("Catalina", 20); Student s4 = new Student("Diana", 20); // 无参的构造方法 TreeMap<String, Student> map = new TreeMap<>(); map.put("Allen", s1); map.put("Beyonce", s2); map.put("Catalina", s3); map.put("Diana", s4);
第二种方法,就是在定义时传入比较器了,Student类不需要实现Comparable接口了
public class Student{ private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
但是在定义时,需要传入一个比较器,如下:
TreeMap<Student, String> map = new TreeMap<>(new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { int cmp = s1.getName().compareTo(s2.getName()); cmp = cmp != 0 ? cmp : s1.getAge() - s2.getAge(); return cmp; } });
两种方法相比较,第二种灵活性更好;