Collections在对自定义对象进行排序时,自定义类需要对compareTo()函数进行重写。
public class Student implements Comparable<Student>{//实现Comparable接口,范型定义为类自己
private String name;
private Integer age;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public Student() {
}
@Override
public int compareTo(Student o) {
return this.getAge() - o.getAge();//按age升序
//return o.getAge() - this.getAge();//按age降序
//return 0;// 0表示所有数据都相等
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
Student good = new Student("good", 19);
Student bad = new Student("bad", 15);
Student normal = new Student("normal", 21);
List<Student> list = new ArrayList<>();
Collections.addAll(list,good,bad,normal);
System.out.println(list);
Collections.sort(list);
System.out.println(list);
}
}
如果用sort带排序参数的方法,则自定义类可以不用写compareTo()方法。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
Student good = new Student("good", 19);
Student bad = new Student("bad", 15);
Student normal = new Student("normal", 21);
List<Student> list = new ArrayList<>();
Collections.addAll(list,good,bad,normal);
System.out.println(list);
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge() - o2.getAge();//按age升序
return o2.getAge() - o1.getAge();//按ag降序
//return 0;
}
});
System.out.println(list);
}
}