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

最近研究了一下对list中的对象进行排序,以前还真不知道可以这么搞.
首先,需要排序的对象需要实现Comparable接口.这个接口需要实现的方法名是public int compareTo(比较对象). 这个方法返回三种状态,大于0的int,等于0的int ,小于0的int.  当当前对象大于比较对象的时候返回大于0的int,以此类推:

Java代码 复制代码
  1. public class Person implements Comparable<Person>{   
  2.     public int compareTo(Person  otherPerson ){   
  3.         Long otherPersonId=otherPerson.getPersonId();   
  4.         int value=1;   
  5.         if (otherPersonId!=null&&this.getPersonId()!=null){   
  6.             if(this.personId<otherPersonId){   
  7.                 value=-1;   
  8.   
  9.             }else if(***){   
  10. 此处省略.....   
  11. }   
  12.         return value;   
  13.     }   
  14. }  
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.
如:

Java代码 复制代码
  1. List personList<Person>=getPersonList();   
  2. Collections.sort(personList);  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值