最近研究了一下对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);
本文介绍如何使用Java实现自定义对象的排序。通过实现Comparable接口并重写compareTo方法,可以为Person对象提供排序逻辑。文章提供了具体的代码示例,并展示了如何利用JDK内置的Collections.sort方法对对象列表进行排序。
199

被折叠的 条评论
为什么被折叠?



