现在的位置: 首页 > 综合 > 正文

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

2018年08月07日 ⁄ 综合 ⁄ 共 957字 ⁄ 字号 评论关闭

最近研究了一下对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. }  

实现了这个接口的person类就可以放入list中进行排序了.用JDK自带的collections.
如:

Java代码 复制代码
  1. List personList<Person>=getPersonList();   
  2. Collections.sort(personList);  

抱歉!评论已关闭.