static
| sort ( List list) Sorts the specified list into ascending order,according to the natural ordering of its elements. | |
static
| sort ( List list, Comparator c) Sorts the specified list according to the orderinduced by the specified comparator. |
API如上
具体使用方法:
第一种方法 :容器内要排序的类必须时下 Comparable 接口,Comparable接口来自 java.lang 包
必须实现下面这个方法:
int | compareTo(T o) Compares this object with the specified object for order. |
例子:
import java.util.*;
public class Main{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add(new Student(2,"aa"));
al.add(new Student(1,"bb"));
al.add(new Student(3,"dd"));
al.add(new Student(3,"cc"));
Collections.sort(al);
Iterator it=al.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
class Student implements Comparable{
int id;
String name;
Student(int id,String name){
this.id=id;
this.name=name;
}
public int compareTo(Object o){
Student s=(Student)o;
int result=(id>s.id)?1:((id==s.id)?0:-1);
if(0==result){
result=name.compareTo(s.name);
}
return result;
}
public String toString(){
return "id="+this.id+",name="+this.name;
}
}
第二种方法:使用静态内部类实现Comparator接口,Comparator接口位于java.util包下
int | compare(T o1, T o2) Compares its two arguments for order. |
boolean | equals(Object obj) Indicates whether some other object is "equal to" this Comparator. |
只需实现compare方法就行,equals方法在obeject类就会有,而实体类继承自object类,就必然会有equals方法,所以不需实现
import java.util.*;
public class Main{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add(new Student(2,"aa"));
al.add(new Student(1,"bb"));
al.add(new Student(3,"dd"));
al.add(new Student(3,"cc"));
Collections.sort(al,new StudentComparator());
Iterator it=al.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
class Student {
int id;
String name;
Student(int id,String name){
this.id=id;
this.name=name;
}
public String toString(){
return "id="+this.id+",name="+this.name;
}
}
class StudentComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
int result=(s1.id>s2.id)?1:((s1.id==s2.id)?0:-1);
if(0==result){
result=s1.name.compareTo(s2.name);
}
return result;
}
}
来源:http://www.blogjava.net/xiami1022/archive/2006/11/22/82753.html