|
常用鏈接
留言簿(4)
隨筆檔案(16)
相冊
最新隨筆
積分與排名
最新評論

閱讀排行榜
評論排行榜
Powered by: 博客園
模板提供:滬江博客
|
|
|
|
|
發新文章 |
|
|
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 order ?induced 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; ??????? } ??? } }
|
|