Java中对集合的排序有两种支持
(1): Collections.sort(List<T> list);
(2): Collections.sort(List<T> list, Comparator<? super T> c);
一:第一种方式
参数list必须实现了comparable接口,覆盖掉其compareTo()方法。也就是让sort给你排序,你就必须告诉它什么是大什么是小?类似于C++中的快排qsort。不过查API之后发现Java这里采用的是归并排序。
二:第二种方式
多了一个参数:一个实例化了"继承自Comparator接口的类"的对象。同样继承Comparator接口,就必须覆盖其compare()方法。作用一样,同样是告诉两个元素什么是小什么是大?也就是什么在前什么在后。
总结:两种方式内涵一样,排序框架采用归并排序。你只需告诉它什么是小什么是大即可。告诉的方式不同而已。如果存储元素天然的就需要和同类元素作比较(如String),那么毫无疑问,让它实现comparable接口,覆写compareTo()方法。对这种元素集合排序采用第一种即可;如果存储元素间很少相互比较,那么也就没有必要让其实现comparable接口了,也就没有compareTo()方法了,那么只能通过其他方法告诉什么是小什么是大了,方法就是传进去第二个参数:"继承自Comparator接口的类"的对象。
平时需要排序的时候要灵活选用。示例代码如下:
public class Student implements Comparable<Student> { private int id; private String name; private String collegeId; public Student(int id, String name, String collegeId) { super(); this.id = id; this.name = name; this.collegeId = collegeId; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCollegeId() { return collegeId; } public void setCollegeId(String collegeId) { this.collegeId = collegeId; } @Override public int compareTo(Student anotherStudent) { if(this.id > anotherStudent.id){ return 1; } else if(this.id < anotherStudent.id){ return -1; } return 0; } @Override public String toString() { return id + " " + name + " " + collegeId; } }
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class MySort { private List<Student> studentList = new ArrayList<Student>(); public static void main(String[] args){ MySort mySort = new MySort(); mySort.studentList.add(new Student(5, "richard", "CS")); mySort.studentList.add(new Student(4, "rosell", "CS")); mySort.studentList.add(new Student(8, "mei", "CS")); //方法一 Collections.sort(mySort.studentList); //方法二 Collections.sort(mySort.studentList, new Comparator<Student>(){ @Override public int compare(Student s1, Student s2) { if(s1.getId() > s2.getId()){ return 1; } else if(s1.getId() < s2.getId()){ return -1; } return 0; } }); System.out.println(mySort.studentList.get(0)); System.out.println(mySort.studentList.get(1)); System.out.println(mySort.studentList.get(2)); } }