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 ...
随机推荐
- memcached使用文档
使用memcached进行内存缓存 通常的网页缓存方式有动态缓存和静态缓存等几种,在ASP.NET中已经可以实现对页面局部进行缓 存,而使用memcached的缓存比ASP.NET的局部缓存更加灵活, ...
- Solr6.6 Tomcat8部署
原文:https://github.com/x113773/testall/issues/6 准备工作:[solr-6.6.0](http://www.apache.org/dyn/closer.lu ...
- [leetcode-551-Student Attendance Record I]
You are given a string representing an attendance record for a student. The record only contains the ...
- 遇到ANDROID “call to opengl es api with no current context”错误
延迟线程执行 Timer timer=new Timer();//实例化Timer类 timer.schedule(new TimerTask(){ public void run(){ buyed( ...
- Log4Net不同日志类型写入到不同文件
1. 一直在用log4net,从来没有自己整理过.实践出真知,只有自己整理过才能真正掌握. 2. log4net,应该读logfornet,以前一直说log4,log4............ 安装 ...
- win32SDK的hello,world程序(二)
接上篇,原生的控件都不太好看,所以决定自己画一个,稍微处理下消息就能用了.不过,美化这东西是需要天赋的.即使技术再好,没有对UI布局调整和良好的审美能力,做出来的东西还是很挫. 主要把消息逻辑和画的过 ...
- 集成 ssh第一阶段
1.添加spring支持,包含spring-hibernate和spring-struts2.添加struts支持,包含struts-spring3.添加hibernate支持,在spring配置文件 ...
- 关于IO流代码BufferedReader
package JBJADV003;import java.io.*;public class BufferedReaderTest { /** * @param args */ public sta ...
- Maven学习专题--Maven入门及安装
因为项目需要,新项目需要使用Maven开发,但是组内大部分没有接触过maven.我就毅然承担搭建maven环境的任务了.因为一切重头开始,就想把自己的整个搭建环境.项目创建.框架整合和模块管理整个过程 ...
- Spring3 MVC 类型转换
1. Spring在进行类型转化都是基于java.beans.PropertyEditor接口. 2. 可以使用@InitBinder来进行对单个controller的类型进行操作,比如添加Date类 ...