对于数组排序我们知道有Arrays.sort()方法,但是如果遇到想要对一个对象数组中的某个属性进行排序,我们该如何去做呢?
以给学生成绩排序为例,首先创建一个存储学生对象的数组。
- package JAVA_API;
-
- public class Sort_oop {
- public static void main(String[] args) {
- Student[] s=new Student[10];
- s= new Student[]{
- new Student("adele", 90, 22),
- new Student("happy", 80, 23),
- new Student("love", 99, 19),
- new Student("cat", 78, 19),
- new Student("dog", 66, 19),
- new Student("momo", 50, 19),
- new Student("rabbit", 89, 19),
- new Student("apple", 56, 19),
- new Student("love", 99, 19),
- new Student("love", 99, 19)
- };
-
- }
- }
创建学生类
- package JAVA_API;
-
- public class Student {
- String name;
- int score;
- int age;
-
- public Student(String name, int score, int age) {
- this.name=name;
- this.age=age;
- this.score=score;
- }
-
- }
此时该如何对学生成绩进行排序呢?
当我们直接进行Arrays.sort(s)排序时

出现了以下情况---ClassCastException (类转换异常)

我们还看见后面显示JAVA_API.Student cannot be cast to java.lang.Comparable (需要实现Comparable接口)
如图,同样是类,为什么在给String类型数组排序时就不会出现当前情况呢?


因为在String的底层已经实现了Comparable的接口。


因此,想要实现我们自定义类的属性排序,我们需要对 Student类实现接口

重写方法之后
- package JAVA_API;
-
- public class Student implements Comparable
{ - String name;
- int score;
- int age;
-
- public Student(String name, int score, int age) {
- this.name=name;
- this.age=age;
- this.score=score;
- }
- @Override
- public String toString() {
- return "Student{" +
- "name='" + name + '\'' +
- ", score=" + score +
- ", age=" + age +
- '}';
- }
-
- @Override
- public int compareTo(Student o) {
- return this.score-o.score;
- }
- }
运行程序成功。
