项目过程当中遇到 类的排序 能够用这个类实现Comparable接口 ,重写comparaeTo方法来对这个类进行排序java
在这个方法中 若是返回-1,则当前对象排在前面,若是返回1 ,则当前对象排在后面 ,返回0 .则相等ide
多的不说 直接上代码测试
实体类 :Student
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @authot Administrator
* @create 2018-05-20 13:43
*/
public class Student implements Comparable<Student>{
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);
}
}
}
}
里面三个字段 ,数量,总额,和建立时间 先比较数量 再比较总额 ,最后比较时间,通常到时间维度也就比较出来了this
在比较时间的维度 的时候直接使用compareTo方法 由于在日期类中已经对compareTo方法作了重写 因此能够直接比较code
测试类:orm
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{
List<Student> students = new ArrayList<Student>();
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:03
number:4;money:100.0;createdate:2018-05-20 13:16:02
number:3;money:200.0;createdate:2018-05-20 13:14:02
number:3;money:500.0;createdate:2018-05-20 13:08:02
number:2;money:300.0;createdate:2018-05-20 13:20:02
number:1;money:400.0;createdate:2018-05-20 13:01:02
number:1;money:600.0;createdate:2018-05-20 13:08:02排序
第一次写博客但愿能够对你获得帮助,多多指教接口