以Student类为例子
1. Comparable
当使用Comparable接口对学生类进行排序时,需要在Student类中实现Comparable接口,并重写compareTo方法。之后在实例化Student后,对其通过sort进行排序。实现如下:
package com.example.helloworld;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Student otherStudent) {
// 根据年龄比较学生
return Integer.compare(this.age, otherStudent.getAge());
//另一种写法:
// return this.age - otherStudent.age;
}
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 20));
students.add(new Student("Bob", 22));
students.add(new Student("Charlie", 19));
Collections.sort(students);
for (Student student : students) {
System.out.println(student.getName() + " - " + student.getAge());
}
}
}
***(return this.age - otherStudent.age)表示升序,同理,(return otherStudent.age-this.age )***就表示降序!
2. Comparator
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 20));
students.add(new Student("Bob", 22));
students.add(new Student("Charlie", 19));
Comparator<Student> comparator = new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return Integer.compare(s1.getAge(), s2.getAge());
}
};
students.sort(comparator);
// 使用 Comparator 对学生列表按年龄进行排序
// 或者使用 lambda 表达式
// students.sort(new Comparator<Student>() {
// @Override
// public int compare(Student s1, Student s2) {
//
// return Integer.compare(s1.getAge(), s2.getAge());
// }
// });
for (Student student : students) {
System.out.println(student.getName() + " - " + student.getAge());
}
}
}