TreeSet排序器
1.自然排序器
1.自定义的实体类实现comparable接口覆写其中的compareTo(Object o);
2.根据业务逻辑设定排序
2.定制排序器
1.自定义的类实现comparator接口覆写其中的compare(Object o1, Object o2);
2.根据业务逻辑设定排序
3.定制排序器需要在创建集合时传参才会有效果,否则会默认执行自然排序器
3.实例演示
package homework;
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetDemo3 {
public static void main(String[] args) {
TreeSet<Student3> ts = new TreeSet<Student3>(new MyComparator3());
ts.add(new Student3("zs", 17, 18));
ts.add(new Student3("ls", 18, 20));
ts.add(new Student3("ww", 22, 19));
ts.add(new Student3("ll", 18, 19));
System.out.println(ts);
}
}
//自定义比较器 第三方比较器
class MyComparator3 implements Comparator {
@Override
public int compare(Object o1, Object o2) {
// 判空
if (o1 instanceof Student3 && o2 instanceof Student3) {
// 强转
Student3 stu1 = (Student3) o1;
Student3 stu2 = (Student3) o2;
if (stu1.getAge() > stu2.getAge()) {
return 1;
} else if (stu1.getAge() < stu2.getAge()) {
return -1;
} else {
return stu1.compareTo(stu2);
}
}
return 0;
}
}
//学生实体类 默认比较器
class Student3 implements Comparable {
private String name;
private int age;
private int height;
public Student3(String name, int age, int height) {
this.name = name;
this.age = age;
this.height = height;
}
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;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public int compareTo(Object o) {
// 判空
if (o instanceof Student3) {
// 强转
Student3 stu = (Student3) o;
if (stu.getHeight() > this.getHeight()) {
return -1;
} else if (stu.getHeight() > this.getHeight()) {
return 1;
}
}
return 0;
}
@Override
public String toString() {
return " [name=" + name + ", age=" + age + ", height=" + height + "]";
}
}
4.注意
定制排序器比自然排序器优先级高,即在定制排序器排完之后,在不破坏定制排序器的规则下,可用自然排序器进行二次排序