且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-03-16 04:51:56

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