• java中的自定义对象排序


    对于数组排序我们知道有Arrays.sort()方法,但是如果遇到想要对一个对象数组中的某个属性进行排序,我们该如何去做呢?

    以给学生成绩排序为例,首先创建一个存储学生对象的数组。

    1. package JAVA_API;
    2. public class Sort_oop {
    3. public static void main(String[] args) {
    4. Student[] s=new Student[10];
    5. s= new Student[]{
    6. new Student("adele", 90, 22),
    7. new Student("happy", 80, 23),
    8. new Student("love", 99, 19),
    9. new Student("cat", 78, 19),
    10. new Student("dog", 66, 19),
    11. new Student("momo", 50, 19),
    12. new Student("rabbit", 89, 19),
    13. new Student("apple", 56, 19),
    14. new Student("love", 99, 19),
    15. new Student("love", 99, 19)
    16. };
    17. }
    18. }

    创建学生类

    1. package JAVA_API;
    2. public class Student {
    3. String name;
    4. int score;
    5. int age;
    6. public Student(String name, int score, int age) {
    7. this.name=name;
    8. this.age=age;
    9. this.score=score;
    10. }
    11. }

    此时该如何对学生成绩进行排序呢?

    当我们直接进行Arrays.sort(s)排序时

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

    我们还看见后面显示JAVA_API.Student cannot be cast to java.lang.Comparable (需要实现Comparable接口)

    如图,同样是类,为什么在给String类型数组排序时就不会出现当前情况呢?

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

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

    重写方法之后

    1. package JAVA_API;
    2. public class Student implements Comparable{
    3. String name;
    4. int score;
    5. int age;
    6. public Student(String name, int score, int age) {
    7. this.name=name;
    8. this.age=age;
    9. this.score=score;
    10. }
    11. @Override
    12. public String toString() {
    13. return "Student{" +
    14. "name='" + name + '\'' +
    15. ", score=" + score +
    16. ", age=" + age +
    17. '}';
    18. }
    19. @Override
    20. public int compareTo(Student o) {
    21. return this.score-o.score;
    22. }
    23. }

     运行程序成功。

  • 相关阅读:
    Android 开发板接入外接USB键盘App重启问题
    利用FastReport传递图片参数,在报表上展示签名信息
    第2讲:Vue开发环境的搭建及运行
    【Java】数组详解
    NLP - 数据预处理 - 文本按句子进行切分
    聊一聊DTM子事务屏障功能之SQL Server版
    动态爱心-详细教程(小白也会)(HTML)
    GIT技巧
    SpringBoot图片验证码
    自定义下拉框级联方法
  • 原文地址:https://blog.csdn.net/m0_71385141/article/details/133076934