Collections.sort()方法的使用及Comparable和comparator的qubie

来源:互联网 发布:芈十四知乎 编辑:程序博客网 时间:2024/05/21 21:44
在介绍sort()方法之前需要先了解一下Comparable和comparator的区别

一、Comparable简介

 Comparable是排序接口。若一个类实现了Comparable接口,就意味着该类支持排序。实现了Comparable接口的类的对象的列表或数组可以通过Collections.sort或Arrays.sort进行自动排序。

此外,实现此接口的对象可以用作有序映射中的键或有序集合中的集合,无需指定比较器。该接口定义如下:、

package java.lang;import java.util.*;public interface Comparable<T> 
{   
public int compareTo(T o);}T表示可以与此对象进行比较的那些对象的类型。

 此接口只有一个方法compare,比较此对象与指定对象的顺序,如果该对象小于、等于或大于指定对象,则分别返回负整数、零或正整数。

  现在我们假设一个Person类,代码如下:

现在有两个Person类的对象,我们如何来比较二者的大小呢?我们可以通过让Person实现Comparable接口:

复制代码
public class Person implements Comparable<Person>{    String name;    int age;    public Person(String name, int age)    {        super();        this.name = name;        this.age = age;    }    public String getName()    {        return name;    }    public int getAge()    {        return age;    }    @Override    public int compareTo(Person p)    {        return this.age-p.getAge();    }    public static void main(String[] args)    {        Person[] people=new Person[]{new Person("xujian", 20),new Person("xiewei", 10)};        System.out.println("排序前");        for (Person person : people)        {            System.out.print(person.getName()+":"+person.getAge());        }        Arrays.sort(people);        System.out.println("\n排序后");        for (Person person : people)        {            System.out.print(person.getName()+":"+person.getAge());        }    }}
程序执行结果为:
排序前:xujian:20xiewei:10
排序后:xiewei:10xujian:20

二、Comparator简介

  Comparator是比较接口,我们如果需要控制某个类的次序,而该类本身不支持排序(即没有实现Comparable接口),那么我们就可以建立一个“该类的比较器”来进行排序,这个“比较器”只需要实现Comparator接口即可。也就是说,我们可以通过实现Comparator来新建一个比较器,然后通过这个比较器对类进行排序。该接口定义如下

package java.util;public interface Comparator<T> {    int compare(T o1, T o2);    boolean equals(Object obj); }

注意:1、若一个类要实现Comparator接口:它一定要实现compareTo(T o1, T o2) 函数,但可以不实现 equals(Object obj) 函数。

   2、int compare(T o1, T o2) 是“比较o1和o2的大小”。返回“负数”,意味着“o1比o2小”;返回“零”,意味着“o1等于o2”;返回“正数”,意味着“o1大于o2”。

  现在假如上面的Person类没有实现Comparable接口,该如何比较大小呢?我们可以新建一个类,让其实现Comparator接口,从而构造一个“比较器"。

public class PersonCompartor implements Comparator<Person>{    @Override    public int compare(Person o1, Person o2)    {        return o1.getAge()-o2.getAge();    }}
public class Person{    String name;    int age;    public Person(String name, int age)    {        super();        this.name = name;        this.age = age;    }    public String getName()    {        return name;    }    public int getAge()    {        return age;    }    public static void main(String[] args)    {        Person[] people=new Person[]{new Person("xujian", 20),new Person("xiewei", 10)};        System.out.println("排序前");        for (Person person : people)        {            System.out.print(person.getName()+":"+person.getAge());        }        Arrays.sort(people,new PersonCompartor());        System.out.println("\n排序后");        for (Person person : people)        {            System.out.print(person.getName()+":"+person.getAge());        }    }}
程序运行结果为:

排序前:xujian:20xiewei:10排序后xiewei:10xujian:20

三、Comparable和Comparator区别比较

  Comparable是排序接口,若一个类实现了Comparable接口,就意味着“该类支持排序”。而Comparator是比较器,我们若需要控制某个类的次序,可以建立一个“该类的比较器”来进行排序。

  Comparable相当于“内部比较器”,而Comparator相当于“外部比较器”。

Comparator位于包java.util下,而Comparable位于包java.lang下

  两种方法各有优劣, 用Comparable 简单, 只要实现Comparable 接口的对象直接就成为一个可以比较的对象,但是需要修改源代码。 用Comparator 的好处是不需要修改源代码, 而是另外实现一个比较器, 当某个自定义的对象需要作比较的时候,把比较器和对象一起传递过去就可以比大小了, 并且在Comparator 里面用户可以自己实现复杂的可以通用的逻辑,使其可以匹配一些比较简单的对象,那样就可以节省很多重复劳动了。

四、Collections.sort()的用法

用Collections.sort方法对list排序有两种方法
第一种是list中的对象实现Comparable接口,如下:
第二种方法是根据Collections.sort重载方法来实现,例如:
public class TestSort {
  public static void main(String args[]) {
    Student A = new Student(2, "b", "2");
    Student B = new Student(1, "a", "1");
    Student C = new Student(3, "a", "1");
    List<Student> sortStudent = new ArrayList<Student>();
    sortStudent.add(B);
    sortStudent.add(A);
    sortStudent.add(C);
    Collections.sort(sortStudent, new Comparator<Student>() {
      @Override
      public int compare(Student o1, Student o2) {
        if (o1.getId() == null) {
          return 1;
        }
        if (o2.getId() == null) {
          return -1;
        }
        return o2.getId().compareTo(o1.getId());
      }
    });
    for (Student item : sortStudent) {
      System.out.println("id:" + item.getId() + ",name:" + item.getName());
    }
    List<Integer> sortIntegerList = new ArrayList<Integer>();
    sortIntegerList.add(2);
    sortIntegerList.add(3);
    sortIntegerList.add(1);
    sortIntegerList.add(5);
    Collections.sort(sortIntegerList, new Comparator<Integer>() {
      @Override
      public int compare(Integer a, Integer b) {
        if (a == null) {
          return 1;
        }
        if (b == null) {
          return -1;
        }
        return b.compareTo(a);
      }     
    });
    for (Integer item : sortIntegerList) {
      System.out.println("id:" + item);
    }
    // Java-collections总结http://blog.csdn.net/qq924862077/article/details/48022135
    // http://blog.csdn.net/tjcyjd/article/details/6804690
    // http://www.blogjava.net/landor2004/articles/sort.html
    // Comparable接口的实现和使用:http://www.cnblogs.com/gnuhpc/archive/2012/12/17/2822251.html
    // Collections.sort对List排序的两种方法:http://blog.csdn.net/wxx614817/article/details/50628197
  }
}

打印结果 id:3,name=a

id:2,name:b

id:1,name:a

id:5

id:3

id:2

id:1

Student 类

  1. public class Student implements Serializable, Comparable<Student> {
  2.   private static final long serialVersionUID = 6801266291633905726L;
  3.   private Integer id;
  4.   private String name;
  5.  private String sno;
  6.   public Integer getId() {
  7.     return id;
  8.   }

  9.   public void setId(Integer id) {
  10.     this.id = id;
  11.   }

  12.   public String getName() {
  13.     return name;
  14.   }

  15.   public void setName(String name) {
  16.     this.name = name;
  17.   }

  18.   public String getSno() {
  19.     return sno;
  20.   }

  21.   public void setSno(String sno) {
  22.     this.sno = sno;
  23.   }

  24.   public Student() {

  25.   }


  26.   public Student(Integer id, String name, String sno) {
  27.     this.id = id;
  28.     this.name = name;
  29.     this.sno = sno;
  30.   }

  31.   @Override
  32.   public int compareTo(Student o) {
  33.     return this.id - o.id;
  34.   }


}

阅读全文
0 0
原创粉丝点击