2008-03-28
如何对List中的对象进行排序
关键字: list 排序
最近研究了一下对list中的对象进行排序,以前还真不知道可以这么搞.
首先,需要排序的对象需要实现Comparable接口.这个接口需要实现的方法名是public int compareTo(比较对象). 这个方法返回三种状态,大于0的int,等于0的int ,小于0的int. 当当前对象大于比较对象的时候返回大于0的int,以此类推:
实现了这个接口的person类就可以放入list中进行排序了.用JDK自带的collections.
如:
首先,需要排序的对象需要实现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);
- 09:24
- 浏览 (144)
- 评论 (2)
- 分类: 计算机与 Internet
- 进入论坛
- 相关推荐
评论
darkjune
2008-03-28
恩,是这样的,我为了方便直接实现comparable接口
spiritfrog
2008-03-28
不是这样吧,list本身就是无序的。
应该用Comparator,Collections.sort(personList, comparator);
应该用Comparator,Collections.sort(personList, comparator);
发表评论
提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则
- 浏览: 18466 次

- 详细资料
搜索本博客
我的相册
siebel
共 1 张
共 1 张
最近加入圈子
最新评论
-
eclipse自带内存监视及回 ...
呵呵,不用~
-- by darkjune -
eclipse自带内存监视及回 ...
原来是自带的! 谢谢了!!!
-- by grape927 -
webwork数组形式提交表单 ...
可曾解决过 webwork/struts2中如何给一个对象的集合对象配置参数 的 ...
-- by xzcgeorge -
如何对List中的对象进行排 ...
恩,是这样的,我为了方便直接实现comparable接口
-- by darkjune -
如何对List中的对象进行排 ...
不是这样吧,list本身就是无序的。 应该用Comparator,Collect ...
-- by spiritfrog






评论排行榜