2008-03-28

如何对List中的对象进行排序

关键字: 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);
评论
darkjune 2008-03-28
恩,是这样的,我为了方便直接实现comparable接口
spiritfrog 2008-03-28
不是这样吧,list本身就是无序的。
应该用Comparator,Collections.sort(personList, comparator);
发表评论

提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则

您还没有登录,请登录后发表评论

darkjune
搜索本博客
我的相册
45a46d56-bef4-4041-ba1f-3dbf35966fe7-thumb
siebel
共 1 张
最近加入圈子
存档
最新评论