static
| sort ( List <T> list) Sorts the specified list into ascending order, according to the natural ordering of its elements. | |
static
| sort ( List <T> list, Comparator <? super T> 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<Student> al=new ArrayList<Student>();
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<Student> al=new ArrayList<Student>();
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 Student.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;
}
static 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;
}
}
}