对Comparable 的解释

Comparable是一个排序接口

此接口给实现类提供了一个排序的方法,此接口有且只有一个方法

public int compareTo(T o);

compareTo方法接受任意类型的参数,来进行比较

list或者数组实现了这个接口能够自动的进行排序,相关类的方法有Collections.sort(),Arrays.sort();

SortedMap 接口的key内置了compareTo方法来进行键排序,SortedSet 也是内置了compareTo方法作为其内部元素的比较手段

compareTo()方法与equals()方法的比较

compareTo()方法不同于equals()方法,它的返回值是一个int类型

int a = 10,b = 20,c = 30,d = 30;
a.compareTo(b) // 返回 -1 说明 a 要比 b 小
c.compareTo(b) // 返回 1 说明 c 要比 b 大
d.compareTo(c) // 返回 0 说明 d 和c 相等

而equals 方法返回的是boolean 类型

x.equals(y) // true 说明x 与 y 的值 相等 , false 说明x 与 y 的值 不相等

代码

Comparable 更像是一个内部排序接口,一个类实现了Comparable比较器,就意味着它本身支持排序;可以用Collections.sort() 或者 Arrays.sort() 进行排序

public class Student implements Comparable<Student>{

    String name;
int record; public Student(){}
public Student(String name,int record){
this.name = name;
this.record = record;
} public boolean equals(Student student) {
// 拿名字和成绩进行对比
return name.equals(student.name)
&& record == student.record;
} @Override
public int compareTo(Student stu) {
// 调用String 类的compareTo方法,返回值 -1,0,1
return this.name.compareTo(stu.name);
} get and set...
} public class ComparableTest { public static void main(String[] args) {
List<Student> studentList = Arrays.asList(new Student("liming", 90),
new Student("xiaohong", 95),
new Student("zhoubin", 88),
new Student("xiaoli", 94)
);
// 排序前
System.out.println(studentList);
Collections.sort(studentList);
// 排序后
System.out.println(studentList); for(Student student : studentList){
System.out.println(student.equals(new Student("xiaohong", 95)));
}
}
}

输出:

[liming = 90, xiaohong = 95, zhoubin = 88, xiaoli = 94]

[liming = 90, xiaohong = 95, xiaoli = 94, zhoubin = 88]

false

true

false

false

对 Arrays.asList() 的解释说明 http://xxxx.com

compareTo()方法抛出异常

public int compareTo(T o);

NullPointerException : 如果 对象o为null,抛出空指针异常

ClassCastException: 如果需要类型转换之后进行比较,可能会抛出ClassCastException

对Comparator 的解释

Comparator 相当于一个比较器,作用和Comparable类似,也是使用Collections.sort() 和 Arrays.sort()来进行排序,也可以对SortedMap 和 SortedSet 的数据结构进行精准的控制,你可以不用实现此接口或者Comparable接口就可以实现次序比较。 TreeSet 和 TreeMap的数据结构底层也是使用Comparator 来实现。不同于Comparable ,比较器可以任选地允许比较null参数,同时保持要求等价关系。

Comparator比较器的方法

int compare(T o1, T o2);

compare() 方法的用法和Comparable 的 compareTo() 用法基本一样,这个方法不允许进行null值比较,会抛出空指针异常

boolean equals(Object obj);

jdk1.8 之后又增加了很多新的方法

很多都是关于函数式编程的,在这里先不做讨论了

代码实现

public class AscComparator implements Comparator<Student> {

    @Override
public int compare(Student stu1, Student stu2) { // 根据成绩降序排列
return stu1.getRecord() - stu2.getRecord();
} } public class ComparatorTest { public static void main(String[] args) {
List<Student> studentList = Arrays.asList(new Student("liming", 90),
new Student("xiaohong", 95),
new Student("zhoubin", 88),
new Student("xiaoli", 94)
);
// 1. 可以实现自己的外部接口进行排序
Collections.sort(studentList,new AscComparator()); System.out.println(studentList); // 2、 可以匿名内部类实现自定义排序
Collections.sort(studentList, new Comparator<Student>() {
@Override
public int compare(Student stu1, Student stu2) {
return stu2.getRecord() - stu1.getRecord();
}
});
System.out.println(studentList);
}
}

也可以使用Arrays.sort()进行排序,不过针对的数据结构是数组。

Comparable 和 Comparator 的对比

1、Comparable 更像是自然排序

2、Comparator 更像是定制排序

同时存在时采用 Comparator(定制排序)的规则进行比较。

对于一些普通的数据类型(比如 String, Integer, Double…),它们默认实现了Comparable 接口,实现了 compareTo 方法,我们可以直接使用。

而对于一些自定义类,它们可能在不同情况下需要实现不同的比较策略,我们可以新创建 Comparator 接口,然后使用特定的 Comparator 实现进行比较。

参考: Java 中 Comparable 和 Comparator 比较

https://zhuanlan.zhihu.com/p/24081048 Java 解惑:Comparable 和 Comparator 的区别

Comparable 和 Comparator的理解的更多相关文章

  1. Java中Comparable与Comparator的区别

    相同 Comparable和Comparator都是用来实现对象的比较.排序 要想对象比较.排序,都需要实现Comparable或Comparator接口 Comparable和Comparator都 ...

  2. Java中的TreeMap、Comparable、Comparator

    我们知道HashMap的存储位置是按照key这个对象的hashCode来存放的,而TreeMap则是不是按照hashCode来存放,他是按照实现的Comparable接口的compareTo这个方法来 ...

  3. java中Comparable和Comparator两种比较器的区别

    Comparable和Comparator接口都是为了对类进行比较,众所周知,诸如Integer,double等基本数据类型,java可以对他们进行比较,而对于类的比较,需要人工定义比较用到的字段比较 ...

  4. 似懂非懂的Comparable与Comparator

    jdk1.8.0_41 一知半解写代码, 集合排序用个啥. 抄起键盘胡乱打, 似懂非懂最可怕. Comparable与Comparator都是用于集合的排序,对于大多数人来说Comparator可能略 ...

  5. Comparable和Comparator的区别&Collections.sort的两种用法

    在Java集合的学习中,我们明白了: 看到tree,可以按顺序进行排列,就要想到两个接口.Comparable(集合中元素实现这个接口,元素自身具备可比性),Comparator(比较器,传入容器构造 ...

  6. 夯实Java基础(十五)——Java中Comparable和Comparator

    1.前言 对于Java中的对象,我们只能使用基本运算符==.!=来判断一下地址是否相等,不能使用>.<来比较大小.但是在实际的开发中,我们需要对对象进行排序,也就是比较大小,那么应该如何实 ...

  7. TreeSet的两种实现方法:Comparable和Comparator(Java比较器)

    Comparable与Comparator实际上是TreeSet集合的两种实现方式,用来实现对象的排序.下边介绍一下两种比较器的使用方法和区别. Comparable称为元素的自然顺序,或者叫做默认顺 ...

  8. 对象比较器:Comparable和Comparator

    在进行对象数组排序的过程中需要使用到比较器,比较器有两个:Comparable和Comparator ①.java.lang.Comparable:是在类定义是时候默认实现好的接口,里面提供有一个co ...

  9. Java中Comparable和Comparator接口区别分析

    Java中Comparable和Comparator接口区别分析 来源:码农网 | 时间:2015-03-16 10:25:20 | 阅读数:8902 [导读] 本文要来详细分析一下Java中Comp ...

随机推荐

  1. CMDB资源配置管理项目

    浅谈ITIL TIL即IT基础架构库(Information Technology Infrastructure Library, ITIL,信息技术基础架构库)由英国政府部门CCTA(Central ...

  2. win10系统中virtualbox无法安装64位系统

    win10系统中virtualbox无法安装64位系统 先总结下如果想在虚拟机中安装64位的Linux系统,最好能满足这几个条件: 64位CPU 64位操作系统 64位的虚拟机软件 开启BIOS虚拟化 ...

  3. CentOS使用dnf安装Redis

    1.查询可用的redis安装包 输入以下命令: dnf list redis 输出: redis.x86_64 3.2.10-2.el7 2.安装软件 输入以下命令: dnf install redi ...

  4. 【UML】9种图+包图

    导读:在UML的学习中,介绍了9种图,外加一个包图.这9种图和4大关系,可以说是UML的一个核心内容.我根据自己的笔记,以及查阅的一些资料,对这9种图和包图,做一个总结. 一.基本定义 1.1  总体 ...

  5. tomcat的管理(manager)报错403

    管理tomcat的时候遇到了以下问题: 1.刚开始需要用户名密码,不知道用户名和密码是什么,但是输入什么都不正确. 解决办法: 自己在tomcat-users.xml中按格式添加用户 conf文件夹里 ...

  6. iOS 收款计算器算法

    一个收款计算器算法,从之前高仿有赞Demo里面抽离的一个界面 demo 在这里 https://github.com/L-vinCent/calculView_function 显示计算记录 不能连续 ...

  7. Infinite monkey theorem(hdu 3689)

    题意:问随机生成一个长度为m(m<=1000)长度的字符串,出现某个子串s的概率是多少. /* KMP+DP 设f[i][j]表示A生成到第i位,此时B串匹配到第j位的概率. 转移方程为f[i+ ...

  8. Codeforces Round #287 (Div. 2) E. Breaking Good [Dijkstra 最短路 优先队列]

    传送门 E. Breaking Good time limit per test 2 seconds memory limit per test 256 megabytes input standar ...

  9. Objective-C单例模式的常用实现

    oc中单例模式可以使用以下方法来实现 + (YourClass *)sharedInstance { static dispatch_once_t once; static YourClass *sh ...

  10. 在ScrollView添加一个ListView造成的滚动问题的简单解决办法()

    正常来说,在ScrollView添加一个ListView后在真机上只会显示ListView的一行多一点,我也不理解为什么会这样,后来我把ListView的layout_height改成400dip,而 ...