import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Objects;
// 实现 Comparable 接口,指定自然排序规则(按年龄升序)
class Student implements Comparable<Student> {
private String id;
private int age;
private double score;
public Student(String id, int age, double score) {
this.id = id;
this.age = age;
this.score = score;
}
// 重写 equals:学号相同则判定为同一个学生
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(id, student.id);
}
// 重写 hashCode:与 equals 保持一致,基于学号计算
@Override
public int hashCode() {
return Objects.hash(id);
}
// 重写 compareTo:自然排序规则(按年龄升序)
@Override
public int compareTo(Student o) {
return this.age - o.age;
}
// 重写 toString:方便打印输出
@Override
public String toString() {
return "Student{id='" + id + "', age=" + age + ", score=" + score + "}";
}
// getter 方法(供 Comparator 调用)
public double getScore() {
return score;
}
}
public class CompareDemo {
public static void main(String[] args) {
ArrayList<Student> studentList = new ArrayList<>();
studentList.add(new Student("001", 20, 92.5));
studentList.add(new Student("002", 19, 85.0));
studentList.add(new Student("001", 21, 90.0)); // 与第一个学号相同
studentList.add(new Student("003", 22, 88.5));
// 1. 测试 equals 方法
Student s1 = studentList.get(0);
Student s2 = studentList.get(2);
System.out.println("s1 和 s2 是否相等:" + s1.equals(s2)); // true
// 2. 测试 Comparable 自然排序(按年龄升序)
Collections.sort(studentList);
System.out.println("\n按年龄自然排序结果:");
studentList.forEach(System.out::println);
// 3. 测试 Comparator 自定义排序(按成绩降序)
Collections.sort(studentList, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
// 注意:double 不能直接相减,用 Double.compare 避免精度问题
return Double.compare(s2.getScore(), s1.getScore());
}
});
System.out.println("\n按成绩降序自定义排序结果:");
studentList.forEach(System.out::println);
}
}