Java中Collections类的排序sort函数两种用法

时间:2023-03-08 17:23:56
Java中Collections类的排序sort函数两种用法

java中的Colletions类主要实现列表List的排序功能。根据函数参数的传递,具体的排序可以分为 :

1.  自然排序(natural ordering)。

函数原型:sort(List<T> list)
说明:参数是要参与排序列表的List对象                                                               
实例说明:参与排序的列表的元素Student必须实现Comparable接口的
public int compareTo(Object o) 方法,在里面写对比的原则。
然后调用Colletions.sort(排序对象的列表)    
请看如下示例:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
class ArrayListTest{
public static void printElements(Collection c){
  Iterator it = c.iterator();
  while(it.hasNext()){
  System.out.println(it.next());
}
}
public static void main(String[] args){
  ArrayList<Student> al = new ArrayList<Student>();
  al.add(new Student(2,"aora"));
  al.add(new Student(1,"longyu"));
  al.add(new Student(3,"goso"));
  Collections.sort(al);
  printElements(al);
}
}
class Student implements Comparable{
  int num;
  String name;
  Student(int num,String name){
  this.num = num;
  this.name = name;
}
  public int compareTo(Object o) {
    Student s = (Student)o;
    return num > s.num ? 1 : (num == s.num ? 0 : -1);
  };
  public String toString(){
    return "num = " + this.num + ",name = " + this.name;
  }
}

2.  实现比较器(Comparator)接口。

函数原型:sort(List<T> list, Comparator<? super T> c)
说明:第一个参数同左,第二个参数是构建对比规则的对比器Comparator。
实例说明(如下):在参与排序的列表的元素Student中写一个内部类作为
Student的对比器,这个对比器要实现Comparator接口的public int compare(Object o1,
Object o2)方法,然后调用Colletions.sort(排序对象的列表,对比器)

请看如下示例:

 import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Comparator;
class ArrayListTest{
  public static void printElements(Collection c){
8     Iterator it = c.iterator();
    while(it.hasNext()){
10       System.out.println(it.next());
    }
  }
  public static void main(String[] args){
    ArrayList<Student> al = new ArrayList<Student>();
    al.add(new Student(2,"qingan"));
    al.add(new Student(1,"longyu"));
    al.add(new Student(3,"goso"));
    al.add(new Student(2,"aora"));
19     Collections.sort(al,new Student.studentComparator());
20     printElements(al);
   }
}
class Student{
  int num;
  String name;
  Student(int num,String name){
    this.num = num;
    this.name = name;
  }
  static class studentComparator implements Comparator{
    public int compare(Object o1,Object o2){
      Student s1 = (Student)o1;
      Student s2 = (Student)o2;
34       int result = s1.num > s2.num ? 1 : (s1.num == s2.num ? 0 : -1);
// 注意:此处在对比num相同时,再按照name的首字母比较。
      if(result == 0){
37         result = s1.name.compareTo(s2.name);
38       }
      return result;
    }
}
  public String toString(){
    return "num = " + this.num + ",name = " + this.name;
  }
}

(转http://viver120.blog.163.com/blog/static/60072482013010111228695/)