浏览 306 次
|
该帖已经被评为新手帖
|
|
|---|---|
| 作者 | 正文 |
|
时间:2008-03-28 关键字: list 排序
最近研究了一下对list中的对象进行排序,以前还真不知道可以这么搞.
首先,需要排序的对象需要实现Comparable接口.这个接口需要实现的方法名是public int compareTo(比较对象). 这个方法返回三种状态,大于0的int,等于0的int ,小于0的int. 当当前对象大于比较对象的时候返回大于0的int,以此类推:
public class Person implements Comparable<Person>{
public int compareTo(Person otherPerson ){
Long otherPersonId=otherPerson.getPersonId();
int value=1;
if (otherPersonId!=null&&this.getPersonId()!=null){
if(this.personId<otherPersonId){
value=-1;
}else if(***){
此处省略.....
}
return value;
}
}
实现了这个接口的person类就可以放入list中进行排序了.用JDK自带的collections. 如: List personList<Person>=getPersonList(); Collections.sort(personList); 声明:JavaEye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
|
| 返回顶楼 | |
|
时间:2008-03-28
不是这样吧,list本身就是无序的。
应该用Comparator,Collections.sort(personList, comparator); |
|
| 返回顶楼 | |
|
时间:2008-03-28
恩,是这样的,我为了方便直接实现comparable接口
|
|
| 返回顶楼 | |




