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(排序对象的列表,对比器)
请看如下示例:
1 import java.util.ArrayList; 2 import java.util.Collection; 3 import java.util.Collections; 4 import java.util.Iterator; 5 import java.util.Comparator;
6 class ArrayListTest{ 7 public static void printElements(Collection c){ 8 Iterator it = c.iterator(); 9 while(it.hasNext()){ 10 System.out.println(it.next()); 11 } 12 }
13 public static void main(String[] args){ 14 ArrayList<Student> al = new ArrayList<Student>(); 15 al.add(new Student(2,"qingan")); 16 al.add(new Student(1,"longyu")); 17 al.add(new Student(3,"goso")); 18 al.add(new Student(2,"aora")); 19 Collections.sort(al,new Student.studentComparator()); 20 printElements(al); 21 } 22 }
23 class Student{ 24 int num; 25 String name; 26 Student(int num,String name){ 27 this.num = num; 28 this.name = name; 29 } 30 static class studentComparator implements Comparator{ 31 public int compare(Object o1,Object o2){ 32 Student s1 = (Student)o1; 33 Student s2 = (Student)o2; 34 int result = s1.num > s2.num ? 1 : (s1.num == s2.num ? 0 : -1); 35 // 注意:此处在对比num相同时,再按照name的首字母比较。 36 if(result == 0){ 37 result = s1.name.compareTo(s2.name); 38 } 39 return result; 40 } 41 } 42 public String toString(){ 43 return "num = " + this.num + ",name = " + this.name; 44 } 45 }
(转http://viver120.blog.163.com/blog/static/60072482013010111228695/)