首先讲一下Comparable接口和Comparator接口,以及他们之间的差异。有助于Collections.sort()方法的使用
  Comparable Comparator
  接口都可以用来实现集合中元素的比较、排序,Comparator位于包java.util下,而Comparable位于包java.lang下,Comparable接口将比较代码嵌入自身类中,而后者在一个独立的类中实现比较。
  像Integer、String等这些基本类型的JAVA封装类都已经实现了Comparable接口,这些类对象本身就支持自比较,直接调用Collections.sort()就可以对集合中元素的排序,无需自己去实现Comparable接口。
  而有些自定义类的List序列,当这个对象不支持自比较或者自比较函数不能满足你的要求时,你可以写一个比较器来完成两个对象之间大小的比较,也就是指定使用Comparator(临时规则排序,也称作专门规则排序),如果不指定Comparator,那么就用自然规则排序,这里的自然顺序就是实现Comparable接口设定的排序方式。
  以泛型为的List序列演示两种排序规则
  1.Comparable自然规则排序
  //在自定义类Student里面实现Comparable接口,并重写抽象方法compareTo(Student o),
  //Collections.sort(集合);
  package Test;
  import java.util.Comparator;
  public class Student implements Comparable{
  public String name;
  public Student(String name){br/>  this.name=name;
  }
  @Override
  public int compareTo(Student o) {
  return this.name.compareTo(o.name);
  }
  }
  package Test;
  import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.Collections;
  import java.util.List;
  public class CollectionTest {
  Student stu=new Student();
  public void test(){
  Listlist=new ArrayList();
  Student students[]={new Student(Tom),new Student(Jack),new Student(Mick)};
  list.addAll(Arrays.asList(students));
  for(Student stu:list){
  System.out.println(stu.name);
  }
  System.out.println(排序后的顺序:);
  Collections.sort(list);
  for(Student stu:list){
  System.out.println(stu.name);
  }
  }
  public static void main(String[] args) {
  CollectionTest ct=new CollectionTest();
  ct.test();
  }
  }
  运行结果:
  
图片描述

  2.Comparator专门规则排序(l临时排序)
  //新建一个实现了Comparator接口的类,并重写抽象方法compare(Student o1, Student o2)
  //Collections.sort(集合,实现了Comparator接口的类的实例化对象);
  package Test;
  import java.util.Comparator;
  public class Student{
  public String name;
  public Student(String name){
  this.name=name;
  }
  public Student() {
  }
  }
  package Test;
  import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.Collections;
  import java.util.List;
  public class CollectionTest {
  Student stu=new Student();
  public void test(){
  Listlist=new ArrayList();
  Student students[]={new Student(Tom),new Student(Jack),new Student(Mick)};
  list.addAll(Arrays.asList(students));
  for(Student stu:list){
  System.out.println(stu.name);
  }
  System.out.println(排序后的顺序:);
  Collections.sort(list,new ComparatorTest());
  for(Student stu:list){
  System.out.println(stu.name);
  }
  }
  public static void main(String[] args) {
  CollectionTest ct=new CollectionTest();
  ct.test();
  }
  }
  package Test;
  import java.util.Comparator;
  public class ComparatorTest implements Comparator{br/>  @Override
  public int compare(Student o1, Student o2) {
  // TODO Auto-generated method stub
  return o1.name.compareTo(o2.name);
  }
  }
  运行结果:
  
图片描述