compareable接口的使用
-
Comparable接口: 是一个比较接口
-
若一个类实现了Comparable接口,就意味着“该类支持排序”。 即然实现Comparable接口的类支持排序,假设现在存在“实现Comparable接口的类的对象的List列表(或数组)”,则该List列表(或数组)可以通过 Collections.sort(或 Arrays.sort)进行排序。
-
此外,“实现Comparable接口的类的对象”可以用作“有序映射(如TreeMap)”中的键或“有序集合(TreeSet)”中的元素,而不需要指定比较器
-
-
需要重写该接口的方法: public int compareTo(Object o)
compareTo()方法
方法比较规则:
返回值为0 默认添加的元素重复,就实现去重
返回值为正 默认添加的元素大,将元素存储在右子树(后取)
返回值为负 默认添加的元素小,将元素存储在左子树(先取)
举例
//person类实现比较接口并重写compareTo方法
public class Person implements Comparable<Person> {
@Override
public int compareTo(Person o) {
// 当前的减去上一次的返回值大,放右边,后取出,所以是从大到小排序
// return this.age-o.age;
//年龄比
int a= this.age-o.age;
//姓名比
int b = this.name.compareTo(o.name);
return a!=0 ? a:b;
}
}
//以上类重写后的方法可以决定测试类中TreeSet集合输出的排序顺序
public class Person_complication {
public static void main(String[] args) {
TreeSet<Person> p = new TreeSet<>();
p.add(new Person("张三",18));
p.add(new Person("李四",15));
p.add(new Person("王五",20));
p.add(new Person("赵六",14));
p.add(new Person("陈八",16));
p.add(new Person("王五",16));
p.add(new Person("周七",22));
System.out.println(p);
}
}
Comparator比较器举例
案例:
使用TreeSet集合存储多个学生信息, 先按照学生的总成绩升序排列 如果总成绩相同,则按照语文成绩升序排列 如果语文成绩也相同,则按照名字的自然排序升序排列 学生类: 属性:姓名 语文成绩 数学成绩
public class Student {
private String name;
private int chinese;
private int math;
private int sum=chinese+math;
public Student() {
}
public Student(String name, int chinese, int math) {
this.name = name;
this.chinese = chinese;
this.math = math;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", chinese=" + chinese +
", math=" + math +
", sum=" + sum +
'}';
}
}
测试类:
重写compare方法实现排序,逻辑与compareTo一样
public class Student_Test {
public static void main(String[] args) {
//使用Comparator比较器,new一个匿名内部类
Comparator c = new Comparator<Student>(){
@Override
public int compare(Student o1, Student o2) {
int sum = o1.getSum() - o2.getSum();//此值大于零时,按成绩升序
int chinese = o1.getChinese() - o2.getChinese();
int name = o1.getName().compareTo(o2.getName());
return sum == 0 ? (chinese == 0 ? name : chinese) : sum;
}
};
//往集合中录入数据
TreeSet<Student> s = new TreeSet<>(c);
s.add(new Student("张三",50,70));
s.add(new Student("李四",60,90));
s.add(new Student("王五",30,95));
s.add(new Student("赵六",40,40));
s.add(new Student("周七",80,20));
System.out.println(s);
}
}