|
常用链接
留言簿(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; } } }
|
|