用Collection是工具类的sort()方法排序
- 自定义元素:为类添加比较功能,实现Comparable接口,重写compareTo方法
对自定义Student类按年龄升序排序 ,代码如下:
public class Student implements Comparable {
@Override
public int compareTo(Object o) {
Student stu=(Student)o;
return this.age-stu.age;
}
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
. . . . . .
=================================
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsTest {
public static void main(String[] args) {
List<Student> list=new ArrayList<>();
list.add(new Student("张三",18));
list.add(new Student("李四",12));
list.add(new Student("王五",26));
list.add(new Student("赵六",19));
//按照年龄升序对student对象进行排序
Collections.sort(list);
for (Student student : list) {
System.out.println(student);
}
}
}
运行结果:
对自定义对象进行比较的前提是要有可以进行排序的属性,比如数字之类的
2. 比较器comparator接口
按照年龄降序排列,代码如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class CollectionsTest2 {
public static void main(String[] args) {
List<Student> studentList=new ArrayList<>();
studentList.add(new Student("jack",27));
studentList.add(new Student("lucy",18));
studentList.add(new Student("jerry",35));
studentList.add(new Student("dane",10));
Collections.sort(studentList, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.getAge()-o1.getAge();
}
});
for (Student student : studentList) {
System.out.println(student);
}
}
}
用匿名内部类的方式实现Comparator重写compare方法
运行结果: