使用Comparable接口的小例子
代码:
public class Student implements Comparable<Student> { private int id; private String name; private int age; public Student(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } @Override public int compareTo(Student o) { if (id > o.id) { return 1; } else if (id < o.id) { return -1; } return 0; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("学生的编号:" + id + ", "); sb.append("学生的姓名:" + name + ", "); sb.append("学生的年龄:" + age); return sb.toString(); } }
测试:
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Test { public static void main(String[] args) { List<Student> list = new ArrayList<Student>(); list.add(new Student(3, "ZhangSan", 21)); list.add(new Student(2, "LiSi", 22)); list.add(new Student(1, "WangWu", 23)); System.out.println("排序前:"); for (Student stu : list) { System.out.println(stu); } System.out.println("排序后:"); Collections.sort(list); // 执行自动排序 for (Student stu : list) { System.out.println(stu); } } }