1.让需要排序的对象实现Comparable接口,并重写compareTo方法
String name;
private int score;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public Student(int age, String name, int score) {
super();
this.age = age;
this.name = name;
this.score = score;
}
@Override
public int compareTo(Student other) { //参数为需要排序的对象
return score-other.getScore(); //表示通过分数score字段进行排序
}
}
2.构造需要排序的对象的集合,并调用Collections.sort()方法对集合中元素进行排序:
public class CompareTest { public static void main(String[] args) { Student s1 = new Student(16, "aa", 44); Student s2 = new Student(18, "bb", 88); Student s3 = new Student(17, "cc", 99); Student s4 = new Student(19, "dd", 66); List<Student> students = Arrays.asList(s1, s2, s3, s4); Collections.sort(students); //对students按score字段进行排序 for (Student student : students) { System.out.println(student.getScore()); } } }
注意:使用 Collections.sort(students);方法对集合对象进行排序时,集合中的对象必须实现Comparable接口,否则报错