最近研究了一下对list中的对象进行排序,以前还真不知道可以这么搞.
首先,需要排序的对象需要实现Comparable接口.这个接口需要实现的方法名是public int compareTo(比较对象). 这个方法返回三种状态,大于0的int,等于0的int ,小于0的int. 当当前对象大于比较对象的时候返回大于0的int,以此类推:
- publicclassPersonimplementsComparable<Person>{
- publicintcompareTo(PersonotherPerson){
- LongotherPersonId=otherPerson.getPersonId();
- intvalue=1;
- if(otherPersonId!=null&&this.getPersonId()!=null){
- if(this.personId<otherPersonId){
- value=-1;
- }elseif(***){
- 此处省略.....
- }
- returnvalue;
- }
- }
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.
如:
- ListpersonList<Person>=getPersonList();
- Collections.sort(personList);
本文介绍如何使用Java实现自定义对象的排序。通过实现Comparable接口并重写compareTo方法,可以使Person类的对象具备比较大小的能力,进而实现排序。文章提供了具体的代码示例,并展示了如何利用JDK自带的Collections工具类进行排序。
859

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



