项目过程中遇到 类的排序 可以用这个类实现Comparable接口 ,重写comparaeTo方法来对这个类进行排序
在这个方法中 如果返回-1,则当前对象排在前面,如果返回1 ,则当前对象排在后面 ,返回0 .则相等
多的不说 直接上代码
实体类 :Student import java.text.SimpleDateFormat; import java.util.Date; /** * @authot Administrator * @create 2018-05-20 13:43 */ public class Student implements Comparable{ private Integer number; private Double money; private Date createdate; public Student (Integer number,Double money,Date createdate) { this.number = number; this.money = money; this.createdate = createdate; } public Integer getNumber() { return number; } public Student setNumber(Integer number) { this.number = number; return this; } public Double getMoney() { return money; } public Student setMoney(Double money) { this.money = money; return this; } public Date getCreatedate() { return createdate; } public Student setCreatedate(Date createdate) { this.createdate = createdate; return this; } @Override public String toString() { return "number:"+number+";money:"+money+";createdate:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createdate); } @Override public int compareTo(Student o) { if (this.number > o.number) { return -1; }else if (this.number < o.number) { return 1; }else{ if (this.money > o.money) { return 1; }else if (this.money < o.money) { return -1; }else { return this.createdate.compareTo(o.createdate); } } } }
里面三个字段 ,数量,总额,和创建时间 先比较数量 再比较总额 ,最后比较时间,一般到时间维度也就比较出来了
在比较时间的维度 的时候直接使用compareTo方法 因为在日期类中已经对compareTo方法做了重写 所以可以直接比较
测试类:
import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; public class Main { public static void main(String[] args) throws Exception{ Liststudents = new ArrayList (); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); students.add(new Student(1,400.0,format.parse("2018-05-20 13:01:02"))); students.add(new Student(2,300.0,format.parse("2018-05-20 13:20:02"))); students.add(new Student(3,200.0,format.parse("2018-05-20 13:14:02"))); students.add(new Student(4,100.0,format.parse("2018-05-20 13:16:02"))); students.add(new Student(5,500.0,format.parse("2018-05-20 13:08:02"))); students.add(new Student(5,500.0,format.parse("2018-05-20 13:08:03"))); students.add(new Student(3,500.0,format.parse("2018-05-20 13:08:02"))); students.add(new Student(1,600.0,format.parse("2018-05-20 13:08:02"))); Collections.sort(students); for (Student student : students) { System.out.println(student); } } }
运行结果如下:
number:5;money:500.0;createdate:2018-05-20 13:08:02
number:5;money:500.0;createdate:2018-05-20 13:08:03number:4;money:100.0;createdate:2018-05-20 13:16:02number:3;money:200.0;createdate:2018-05-20 13:14:02number:3;money:500.0;createdate:2018-05-20 13:08:02number:2;money:300.0;createdate:2018-05-20 13:20:02number:1;money:400.0;createdate:2018-05-20 13:01:02number:1;money:600.0;createdate:2018-05-20 13:08:02
第一次写博客希望可以对你得到帮助,多多指教