1. Comparable: 使类具备排序的能力。
2. Comparator: 自定义的比较器。
Comparable的使用:
package com.yaojun.day4;
import java.util.Comparator;
class Student implements Comparator<Student>{
private String name;
private int no;
private int score;
public Student(String name, int no, int score) {
super();
this.name = name;
this.no = no;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "姓名:"+ name + " 排名:" +no + " 分数:"+score;
}
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return this.score - o2.score;
}
}
public class TestStudent {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student s2 = new Student("太一",2,97);
Student s1 = new Student("妖君",1,99);
Student s3 = new Student("无始",3,96);
Student [] st = {s1,s2,s3};
for (Student student : st) {
System.out.println(student);
}
}
}
结果 :
姓名:妖君 排名:1 分数:99
姓名:太一 排名:2 分数:97
姓名:无始 排名:3 分数:96
如果是一次性的参数传递:可以使用 匿名内部类和lambda表达式
//Lambda表达式
Arrays.sort(st , (o1,o2)->o1.getScore() - o2.getScore());
//匿名内部类
Arrays.sort(st, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.getScore() - o2.getScore();
}
});
for (Student student : st) {
System.out.println(student);
}
}