Java中Comparable与Comparator的区别解析

 更新时间:2024年01月11日 08:37:06   作者:苦糖果与忍冬  
这篇文章主要介绍了Java中Comparable与Comparator的区别解析,实现Comparable接口,重写compareTo方法,一般在实体类定义的时候就可以选择实现该接口,提供一个默认的排序方式,供Arrays.sort和Collections.sort使用,需要的朋友可以参考下

Comparable与Comparator的区别

1.理论知识

Comparable

实现Comparable接口,重写compareTo方法。一般在实体类定义的时候就可以选择实现该接口,提供一个默认的排序方式,供Arrays.sort和Collections.sort使用,只有一种排序方式,很难满足复杂的排序要求。

compareTo方法的返回值是int,有三种情况:

a、当前对象大于被比较对象(compareTo方法里面的形参),返回正整数

b、当前对象等于被比较对象,返回0

c、当前对象小于被比较对象,返回负整数

Comparator

实现Comparator接口,重写compare方法,一般在实体类中未定义排序方法或实体类中的排序方法不满足需求的情况下来实现该接口。实现方法可以是写一个比较器类,也可是匿名内部类。实现方式灵活,可以提供多种排序选择。

Ccompare方法有两个参数o1和o2,分别表示待比较的两个对象,方法返回值也是int,有三种情况:

a、o1大于o2,返回正整数

b、o1等于o2,返回0

c、o1小于o2,返回负整数

2.代码验证

上代码

实体类Student,实现Comparable接口

public class Student implements Comparable<Student> {
    private int age;
    private String address;
    private int score;
    public Student(int age, String address, int score) {
        this.age = age;
        this.address = address;
        this.score = score;
    }
    public int getAge() {
        return age;
    }
    public String getAddress() {
        return address;
    }
    public int getScore() {
        return score;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public void setScore(int score) {
        this.score = score;
    }
    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", address='" + address + '\'' +
                ", score=" + score +
                '}';
    }
    @Override
    public int compareTo(Student o) {
//        return this.age - o.age;
        return o.age - this.age;
    }
}

测试类

public class SortTest {
    public static void main(String[] args) {
        Student s1 = new Student(18, "西安", 98);
        Student s2 = new Student(6, "广州", 68);
        Student s3 = new Student(29, "天水", 84);
        Student s4 = new Student(18, "广州", 84);
        Student[] students = new Student[4];
        students[0] = s1;
        students[1] = s2;
        students[2] = s3;
        students[3] = s4;
        Arrays.sort(students);
//        Arrays.sort(students,new StudentScoreComparator());
//        Arrays.sort(students, new Comparator<Student>() {
//            @Override
//            public int compare(Student o1, Student o2) {
//                return o1.getScore() - o2.getScore();
//            }
//        });
//        Arrays.sort(students, (o1, o2) -> o1.getScore() - o2.getScore());
//        Arrays.sort(students, Comparator.comparingInt(Student::getScore));
        for (int i = 0; i < students.length; i++) {
            System.out.println(students[i]);
        }
    }
}

比较器类

public class StudentScoreComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        if (o1.getScore() == o2.getScore()) {
            return o1.getAge() - o2.getAge();
        }
        return o2.getScore() - o1.getScore();
    }
}
  • 使用默认排序(前提是实体类实现Comparable接口,否则会报错)
Arrays.sort(students);

compareTo方法:用age字段排序

正序:this.age - o.age;

逆序:o.age - this.age;

  • 使用比较器类排序
Arrays.sort(students,new StudentScoreComparator());

compare方法:score逆序,age正序

正序:o1-o2

逆序:o2-o1

匿名内部类排序:score正序

Arrays.sort(students, new Comparator() {
@Override
public int compare(Student o1, Student o2) {
    return o1.getScore() - o2.getScore();
    }
});

lambda简化:

Arrays.sort(students, (o1, o2) -> o1.getScore() - o2.getScore());

正序可以再简化,逆序不行

Arrays.sort(students, Comparator.comparingInt(Student::getScore));

到此这篇关于Java中Comparable与Comparator的区别解析的文章就介绍到这了,更多相关Comparable与Comparator的区别内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 一篇文章带你了解Java中ThreadPool线程池

    一篇文章带你了解Java中ThreadPool线程池

    线程池可以控制运行的线程数量,本文就线程池做了详细的介绍,需要了解的小伙伴可以参考一下
    2021-08-08
  • MyBatis通用Mapper实现原理及相关内容

    MyBatis通用Mapper实现原理及相关内容

    今天小编就为大家分享一篇关于MyBatis通用Mapper实现原理及相关内容,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-12-12
  • Java中类的定义和初始化示例详解

    Java中类的定义和初始化示例详解

    这篇文章主要给大家介绍了关于Java中类的定义和初始化的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • 50 道Java 线程面试题(经典)

    50 道Java 线程面试题(经典)

    java 线程面试题是比较热门的面试题,下面小编给大家分享了50道java线程面试题必掌握,大家来一起学习吧为面试好好准备吧
    2016-11-11
  • Servlet方法生命周期及执行原理详解

    Servlet方法生命周期及执行原理详解

    运行在服务器端的小程序,Servlet就是一个接口,定义了Java类被浏览器访问到(tomcat识别)的规则,将来我们自定义一个类,实现Servlet接口,复写方法
    2021-09-09
  • SpringBoot自定义bean绑定实现

    SpringBoot自定义bean绑定实现

    这篇文章主要介绍了SpringBoot自定义bean绑定,最常见的配置绑定的场景,是在自定义的bean中通过@Value注解将某个属性和对应的配置绑定
    2022-10-10
  • 使用Spring Boot快速构建基于SQLite数据源的应用

    使用Spring Boot快速构建基于SQLite数据源的应用

    为了提供一个单包易部署的服务器应用,考虑使用Spring Boot,因为其集成了Apache Tomcat,易于运行,免去绝大部分了服务器配置的步骤
    2017-08-08
  • SpringMVC异常处理知识点总结

    SpringMVC异常处理知识点总结

    在本篇文章里小编给大家整理的是关于SpringMVC异常处理相关知识点内容,需要的朋友们学习下。
    2019-10-10
  • Java8中Optional类型和Kotlin中可空类型的使用对比

    Java8中Optional类型和Kotlin中可空类型的使用对比

    这篇文章主要给大家介绍了关于Java8中Optional类型和Kotlin中可空类型的使用对比,文中通过示例代码给大家介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
    2017-09-09
  • SpringBoot 内置工具类的使用

    SpringBoot 内置工具类的使用

    本文主要介绍了SpringBoot 内置工具类的使用,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-12-12

最新评论