目录
实现Comparable接口,重写compareTo方法
创建比较器,实现Comparator接口,重写compare方法
创建一个学生类
class Student {
public String name;
public int age;
public Student(String name,int age){
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
执行以下代码
public class Test {
public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student("bit",10);
students[1] = new Student("hello",11);
students[2] = new Student("abc",12);
Arrays.sort(students);
System.out.println(Arrays.toString(students));
}
}
会出现类型转换异常
这是因为我们在进行数组排序的时候,由于我们数组元素的类型是自定义的student类,但是我们没有规定student比较的规则,所以会报错.
在这里,我们可以根据学生的年龄进行排序
class Student implements Comparable{
public String name;
public int age;
public Student(String name,int age){
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Student o) {
return this.age-o.age;
}
}
重写方法后,我们就可以调用此方法来进行学生之间的比较
public static void main(String[] args) {
Student student1 = new Student("zhangsan",15);
Student student2 = new Student("lisi",16);
if (student1.compareTo(student2) > 0){
System.out.println("zhangsan 比 lisi 大!");
}else if (student1.compareTo(student2) == 0){
System.out.println("zhsangsan 和 lisi 一样大!");
}else {
System.out.println("zhangsan 比 lisi 小!");
}
}
上述比较的方法,对类的侵入性比较强,不够灵活,如果改变比较规则,则 需要改动原先的代码.
比较器相对于上述方法能够更加灵活.
如果我们要根据年龄进行比较,就实现一个年龄的比较器.
class AgeComparator implements Comparator{
@Override
public int compare(Student o1, Student o2) {
return o1.age-o2.age;
}
}
如果要根据名字进行比较,就实现一个名字的比较器.
class NameComparator implements Comparator{
@Override
public int compare(Student o1, Student o2) {
return o1.name.compareTo(o2.name);
}
}
public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student("bit",10);
students[1] = new Student("hello",11);
students[2] = new Student("abc",12);
AgeComparator ageComparator = new AgeComparator();
NameComparator nameComparator = new NameComparator();
Arrays.sort(students,nameComparator);
System.out.println(Arrays.toString(students));
}
这样,我们就可以在Arrays.sort方法中传入比较器,根据我们自己制定的比较规则进行比较.
也可以直接调用比较器中的方法进行比较.
public static void main(String[] args) {
Student student1 = new Student("zhangsan",15);
Student student2 = new Student("lisi",16);
AgeComparator ageComparator = new AgeComparator();
int l = ageComparator.compare(student1,student2);
if (l > 0){
System.out.println("s1 > s2");
}else {
System.out.println("s1 < s2");
}
}