1.Comparable简介

此接口对实现它的每个类的对象强加一个总排序。这种排序被称为类的自然排序,类的compareTo方法被称为其自然比较方法。可以通过

Collections.sort(和Arrays.sort)自动对实现此接口的对象的列表(和数组)进行排序。实现此接口的对象可用作有序映射中的键或有序

集中的元素,而无需指定比较器。

注:若一个类实现了该接口,说明该类本身是支持排序的。在java中倡导所有实现Comparable接口的类都应该保持与

equals()一致的排序顺序,因此还需要重写equals方法和hashcode方法。

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method. Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

2.Comparable定义

实现Comparable接口仅需实现compareTo方法。

通过x.compareTo(y)来比较x与y的大小:1)返回负数,说明x小于y;2)返回0,说明x与y相等;3)返回正数,说明x大于y。

 package java.lang;
import java.util.*; public interface Comparable<T> {
public int compareTo(T o);
}

3.Comparator简介

该接口内部是一个比较函数,它对某些对象集合施加总排序。可以将比较器传递给排序方法(例如Collections.sort或Arrays.sort),以便

精确控制排序顺序。比较器还可用于控制某些数据结构的顺序(例如有序集或有序映射),或者为不具有自然顺序的对象集合提供排序。

注:若一个类没有实现Comparable接口,则该类自身无法排序;此时可以使用Comparator帮助这个类进行排序。

A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don't have a natural ordering.

4. Comparator定义

 package java.util;

 public interface Comparator<T> {

     int compare(T o1, T o2);

     boolean equals(Object obj);
}

5. 示例

5.1 Customer.java

该类实现了Comparable接口,即该类的成员对象自身是支持排序的。

 import java.util.Objects;

 public class Customer implements Comparable<Customer>{

     private int customerId;
private String customerName; public Customer(Integer customerId, String customerName) {
this.customerId = customerId;
this.customerName = customerName;
} public int getCustomerId() {
return customerId;
}
public String getCustomerName() {
return customerName;
} @Override
public String toString() {
return "Customer:[Id=" + customerId + ", Name=" + customerName + "]";
} /*
* 重写compareTo方法
* 按Id或者name排序
* 可以对整体添加负号决定升降序
* */
@Override
public int compareTo(Customer o) {
// return this.customerId - o.customerId;
return this.customerName.compareTo(o.customerName);
} /*
* 重写equals和hashcode方法
* 这里id和name相同则为同一对象
* */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Customer)) return false;
Customer customer = (Customer) o;
return customerId == customer.customerId &&
Objects.equals(customerName, customer.customerName);
} @Override
public int hashCode() {
return Objects.hash(customerId, customerName);
} }

5.2 CustomerComparator.java

该类实现了Comparator接口,帮助Customer对象按Id排序。

 import java.util.Comparator;

 public class CustomerComparator implements Comparator<Customer> {

     @Override
public int compare(Customer c1, Customer c2) {
// 按Id排序
return c1.getCustomerId() - c2.getCustomerId();
}
}

5.3 SortFunc.java

使用两种接口的排序方法对list进行排序。

 import java.util.*;

 public class SortFunc {
public static void main(String[] args){
List<Customer> list = new ArrayList<>();
list.add(new Customer(1, "A"));
list.add(new Customer(2, "C"));
list.add(new Customer(3, "D"));
list.add(new Customer(4, "B")); // 原始排序
System.out.println("原始的排序:"+list); // 使用compare接口按name排序
Collections.sort(list);
System.out.println("使用compare接口按name排序:"+list); // 使用comparator接口按id排序
// Collections.sort(list, new CustomerComparator()); // 两个方式
list.sort(new CustomerComparator());
System.out.println("使用comparator接口按id排序:"+list); // 判断c1和c2是否引用同一个对象;判断c1和c2是否等价
Customer c1 = new Customer(6,"c1");
Customer c2 = new Customer(6,"c1");
System.out.println(c1==c2);
System.out.println(c1.equals(c2));
}
}

显示结果如下所示,附带==与equals的说明:

对于引用类型,== 判断两个变量是否引用同一个对象,而 equals() 判断引用的对象是否等价,即数据是否一致。

 原始的排序:[Customer:[Id=1, Name=A], Customer:[Id=2, Name=C], Customer:[Id=3, Name=D], Customer:[Id=4, Name=B]]
使用compare接口按name排序:[Customer:[Id=1, Name=A], Customer:[Id=4, Name=B], Customer:[Id=2, Name=C], Customer:[Id=3, Name=D]]
使用comparator接口按id排序:[Customer:[Id=1, Name=A], Customer:[Id=2, Name=C], Customer:[Id=3, Name=D], Customer:[Id=4, Name=B]]
false
true

!!!

java Comparable and Comparator的更多相关文章

  1. Java Comparable和Comparator

    Java中在进行数据排序时,Comparable和Comparator不可缺少会遇得到.普通的String.Integer等类型,已经实现了Comparable接口,而有些时候,我们须要对一些其它不存 ...

  2. Java Comparable 和 Comparator 接口详解

    本文基于 JDK8 分析 Comparable Comparable 接口位于 java.lang 包下,Comparable 接口下有一个 compareTo 方法,称为自然比较方法.一个类只要实现 ...

  3. java Comparable 和 Comparator接口区别

    Comparable 简介 Comparable 是排序接口. 若一个类实现了Comparable接口,就意味着“该类支持排序”.  即然实现Comparable接口的类支持排序,假设现在存在“实现C ...

  4. Java Comparable与Comparator区别

    1,两种接口的展示 下面的程序是两个类各自实现了Comparable接口.Comparator接口 package com.cnblogs.mufasa.Solution; import java.u ...

  5. Java comparable 和 comparator

    一.comparator 接口继承 public class ComparatorTest { /** * @param args */ public static void main(String[ ...

  6. Java中Comparable与Comparator的区别

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

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

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

  8. Java中Comparable和Comparator区别小结

    一.Comparable简介 Comparable是排序接口.若一个类实现了Comparable接口,就意味着该类支持排序.实现了Comparable接口的类的对象的列表或数组可以通过Collecti ...

  9. Java 中 Comparable 和 Comparator 比较

    Java 中 Comparable 和 Comparator 比较 目录: Comparable Comparator Comparable 和 Comparator比较 第二个例子 之 Compar ...

随机推荐

  1. document.wrtie()用法

    推荐看这篇文章,非常的好 http://www.softwhy.com/article-8326-1.html

  2. IO字节流概念

    1.输入和输出概念: 输入:硬盘到内存为了使用: 输出:内存到硬盘为了保存: 2.一切皆为字节: 计算机只识别二进制数字,一个字节为8个二进制数字: 存储在硬盘是字节,传输也是字节:

  3. java内存机制和GC垃圾回收机制

    Java 内存区域和GC机制 转载来源于:https://www.cnblogs.com/zhguang/p/3257367.html 感谢 目录 Java垃圾回收概况 Java内存区域 Java对象 ...

  4. ECS上nginx搭建反向代理通过内网访问阿里云OSS服务

    对于付不起钱的小伙计,为了给公司省钱,想尽一切招数.今天就来分享一个使用阿里云OSS存储搭配CDN使用的网站服务器部署方法. 简介 阿里云OSS 阿里云提供的一种文件存储方案,和我们以前接触的百度云B ...

  5. 基于vue项目一键国际化通用方案: vue-i18n + i18n-vue-cli(命令行工具)

    鉴于公司有做的国际化需求,对于公司的vue项目,觉得页面还是挺多的.刚开始觉得很简单,就是把vue文件中的中文,替换成变量,提取成一个文件就可以了,谁知道人肉的提取的部分确实太痛苦了,而且容易出错.最 ...

  6. xampp——apache服务启动问题(端口占用)

    Apache启动提示 20:39:02 [Apache] Error: Apache shutdown unexpectedly.20:39:02 [Apache] This may be due t ...

  7. node全局安装说明(create-react-app、)

    1.使用 create-react-app 快速构建 React 开发环境 国内使用 npm 速度很慢,你可以使用淘宝定制的 cnpm (gzip 压缩支持) 命令行工具代替默认的 npm: $ np ...

  8. Mac 虚拟打印机PDFWriter on Sierra

    之前就装过PdfWriter,第一次装的时候失败了,后来在app store 装了PDF Printer,好像挺好用的,但是升级有点贵.又回去研究了一下PDFWriter. 和PDFWriter在so ...

  9. Android中的数据储存

    数据的储存是一个十分重要的功能,它涉及到各种类型的数据,各种的储存方式,今天就接触了Android中数据储存的简单应用,有一种方式是可以将存入的数据原封不动的存储起来,这里要用到openfileout ...

  10. 在微信小程序中将获取到的经纬度(经度纬度)转地址(地名)

    var QQMapWX = require('qqmap-wx-jssdk') var qqmapsdk = new QQMapWX({ key: '填写你的key' // 必填 }) wx.getL ...