一、实体类实现Comparable<Vacation>, Parcelable 接口
eg:public class Vacation implements Comparable<Obj>, Parcelable
二、重写方法compareTo,用于比较两个类的对应的两个属性
eg:
@Override
public int compareTo(Vacation another) {
return this.getTime().compareTo(another.getTime());
}
三、对于获取到的数据List<Obj> objList= new ArrayList<Obj>(),向里面添加好自己将要用来排序的数据,示例如下:
// 升序排列输出 Collections.sort(objList);
// 降序排列输出
Collections.sort(objList, Collections.reverseOrder());
此时objList中的数据就为已经按照个人排序方式排好的数据。
本文介绍如何通过实现Comparable接口并重写compareTo方法来对Java中的自定义类进行排序。具体包括如何定义实体类、实现接口、重写比较方法,并使用Collections.sort进行升序或降序排列。
2887

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



