java中Comparable和Comparator两种比较器的区别
Comparable和Comparator接口都是为了对类进行比较,众所周知,诸如Integer,double等基本数据类型,java可以对他们进行比较,而对于类的比较,需要人工定义比较用到的字段比较逻辑。可以把Comparable理解为内部比较器,而Comparator是外部比较器,基本的写法如下:

class Apple implements Comparable<Apple>{
int id;
double price;
public Apple(int id, double price) {
this.id = id;
this.price = price;
}
public int compareTo(Apple o) {
//return Double.compare(this.getPrice(),o.getPrice());
if (Math.abs(this.price-o.price)<0.001)
return 0;
else
return (o.price-this.price)>0?1:-1;
}
@Override
public String toString() {
return "Apple{" +
"id=" + id +
", price=" + price +
'}';
}
}


class AESComparator implements Comparator<Apple>{
public int compare(Apple o1, Apple o2) {
if (Math.abs(o1.price-o2.price)<0.001)
return 0;
else{
return (o1.price-o2.price)>0?1:-1;
}
}
}

实现了Comparable接口的类需要实现compareTo()方法,传入一个外部参数进行比对,实现了Comparator接口的方法需要实现compare()方法,对外部传入的两个类进行比较,从而让外部方法在比较时调用。
两者的区别是实现Comparator接口代码更加灵活,可以定义某个类的多个比较器,从而在排序时根据实际场景自由调用,而Comparable接口实现后便不能改动。两种接口的调用方式如下:

class AESComparator implements Comparator<Apple>{
public int compare(Apple o1, Apple o2) {
if (Math.abs(o1.price-o2.price)<0.001)
return 0;
else{
return (o1.price-o2.price)>0?1:-1;
}
}
}
class DESComparator implements Comparator<Apple>{
public int compare(Apple o1, Apple o2) {
if (Math.abs(o1.price-o2.price)<0.001)
return 0;
else {
return (o1.price-o2.price)>0?-1:1;
}
}
}


public static void main(String[] args) {
Apple apple1 = new Apple(1,4.8);
Apple apple2 = new Apple(2,5.9);
Apple apple3 = new Apple(3,8.5);
List<Apple> list = new ArrayList<Apple>();
list.add(apple1);
list.add(apple3);
list.add(apple2);
System.out.println("Comparable==========");
System.out.printf("this list of apples: %s\n",list);
Collections.sort(list);
System.out.printf("this list of apples: %s\n",list);
System.out.println("Comparator==========");
System.out.printf("this list of apples: %s\n",list);
Collections.sort(list,new DESComparator());
System.out.printf("this list of apples: %s\n",list);
Collections.sort(list,new AESComparator());
System.out.printf("this list of apples: %s\n",list);
}
}

上述代码存在的问题,不能在比较器中进行double类型的减法操作,因为对于值比较大的double,减法操作容易导致值的溢出,java7对每一种包装类型的比较新增了compare()方法,改造后的代码如下:

class Apple implements Comparable<Apple>{
int id;
double price;
public Apple(int id, double price) {
this.id = id;
this.price = price;
}
public int compareTo(Apple o) {
return Double.compare(this.price,o.price);
}
@Override
public String toString() {
return "Apple{" +
"id=" + id +
", price=" + price +
'}';
}
}
class AESComparator implements Comparator<Apple>{
public int compare(Apple o1, Apple o2) {
return Double.compare(o1.price,o2.price);
}
}
class DESComparator implements Comparator<Apple>{
public int compare(Apple o1, Apple o2) {
return Double.compare(o2.price,o1.price);
}
}

查看Double.compare的源码如下

public static int compare(double d1, double d2) {
if (d1 < d2)
return -1; // Neither val is NaN, thisVal is smaller
if (d1 > d2)
return 1; // Neither val is NaN, thisVal is larger
// Cannot use doubleToRawLongBits because of possibility of NaNs.
long thisBits = Double.doubleToLongBits(d1);
long anotherBits = Double.doubleToLongBits(d2);
return (thisBits == anotherBits ? 0 : // Values are equal
(thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
1)); // (0.0, -0.0) or (NaN, !NaN)
}

java中Comparable和Comparator两种比较器的区别的更多相关文章
- Java中Compareable和Comparator两种比较器的区别
Java中Compareable和Comparator两种比较器的区别 参考原文链接:https://www.cnblogs.com/ldy-blogs/p/8488138.html 1.引言 在ja ...
- Map集合的遍历方式以及TreeMap集合保存自定义对象实现比较的Comparable和Comparator两种方式
Map集合的特点 1.Map集合中保存的都是键值对,键和值是一一对应的 2.一个映射不能包含重复的值 3.每个键最多只能映射到一个值上 Map接口和Collection接口的不同 Map是双列集合的根 ...
- Java中Comparable和Comparator接口区别分析
Java中Comparable和Comparator接口区别分析 来源:码农网 | 时间:2015-03-16 10:25:20 | 阅读数:8902 [导读] 本文要来详细分析一下Java中Comp ...
- Java 中 Comparable 和 Comparator 比较
Java 中 Comparable 和 Comparator 比较 目录: Comparable Comparator Comparable 和 Comparator比较 第二个例子 之 Compar ...
- Java中HashMap遍历的两种方式
Java中HashMap遍历的两种方式 转]Java中HashMap遍历的两种方式原文地址: http://www.javaweb.cc/language/java/032291.shtml 第一种: ...
- java中数组复制的两种方式
在java中数组复制有两种方式: 一:System.arraycopy(原数组,开始copy的下标,存放copy内容的数组,开始存放的下标,需要copy的长度); 这个方法需要先创建一个空的存放cop ...
- Java 中 Comparable 和 Comparator 比较(转)
转自http://www.cnblogs.com/skywang12345/p/3324788.html 本文,先介绍Comparable 和Comparator两个接口,以及它们的差异:接着,通过示 ...
- PHP中数组合并的两种方法及区别介绍
PHP数组合并两种方法及区别 如果是关联数组,如下: 复制代码代码如下: $a = array( 'where' => 'uid=1', 'order' => 'uid', ); $b = ...
- Java中Comparable和Comparator区别小结
一.Comparable简介 Comparable是排序接口.若一个类实现了Comparable接口,就意味着该类支持排序.实现了Comparable接口的类的对象的列表或数组可以通过Collecti ...
随机推荐
- mysql left join
MySQL左连接不同于简单连接.MySQL LEFT JOIN提供该表额外字段在左侧. 如果使用LEFT JOIN,得到的所有记录的匹配方式相同, 在左边表中得到的每个记录不匹配也会有一个额外的记录. ...
- Python进阶 - 命名空间与作用域
Python进阶 - 命名空间与作用域 写在前面 如非特别说明,下文均基于Python3 命名空间与作用于跟名字的绑定相关性很大,可以结合另一篇介绍Python名字.对象及其绑定的文章. 1. 命名空 ...
- 门控开关项目--使用Multism仿真
可以修改桥式整流电路的电容,发现容值不合适的时候,直流不平稳.
- DOCKER 从入门到放弃(二)
搜索镜像 从docker官方镜像仓库搜索镜像 docker search [OPTIONS] TERM OPTIONS: --automated :只显示自动创建的镜像,默认值为fasle --fil ...
- Javascript 类继承
Js继承 JavaScript并不是真正面向对象的语言,是基于对象的,没有类的概念. 要想实现继承,可以用js的原型prototype机制或者用apply和call方法去实现 /** 声明一个基础父类 ...
- 记一次redis挂机导致的服务雪崩事故~不对,是故事
事故时常有,最近特别多!但每次事故总会有人出来背锅!如果不是自己的锅,解决了对自己是一种成长,如果是自己的锅,恐怕锅大了,就得走人了,哈哈哈... 这不,最近又出了一个锅:从周五开始,每天到11点就不 ...
- 数位DP练习
水题 发布时间: 2017年6月22日 19:15 最后更新: 2017年6月23日 20:10 时间限制: 1000ms 内存限制: 128M 描述 给一个数n,求0~n内有多少个数满足 ...
- 【干货】Chrome插件(扩展)开发全攻略(不点进来看看你肯定后悔)
写在前面 我花了将近一个多月的时间断断续续写下这篇博文,并精心写下完整demo,写博客的辛苦大家懂的,所以转载务必保留出处.本文所有涉及到的大部分代码均在这个demo里面:https://github ...
- mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)
最后更新时间:2017-07-13 11:10:49 原始文章链接:http://www.lovebxm.com/2017/07/13/mongodb_primer/ MongoDB - 简介 官网: ...
- js字符串与数组的相互转换
一.数组转字符串,通过join()拼接数组元素 var a, b,c; a = new Array(a,b,c,d,e); b = a.join('-'); c = a.join('');consol ...