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. 【转】2、Jenkins构建完成自动发送邮件

    1.开通163邮箱的授权码服务,和SMTP服务.百度找教程.2.安装 Email Extension Plugin 插件,已安装或版本自带可跳过此步骤.3.进入系统管理–系统设置首先配置 Jenkin ...

  2. echart的x轴换行

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  3. SVN版本服务器搭建(服务端+客户端)

    原文地址:http://www.cnblogs.com/warrior1988/p/5359084.html 环境:Win7 32 bit SVN简介:程序员在编写程序的过程中,每个程序员都会生成很多 ...

  4. Let’s Encrypt 通配符证书申请配置

    首先你可以查看下官方提供的支持申请通配符证书的客户端列表:https://letsencrypt.org/docs/client-options/. 这些客户端支持最新的ACME v2接口,而这个接口 ...

  5. Python母版使用

    设定base.html为母版,母版是页面的公共部分,可以减少代码冗余: 母版中变化的部分用:  {% block page-main % }  <!--page-mains是自己起的名称--&g ...

  6. UITextField只能输入数字NSCharacterSet实现

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementS ...

  7. js 控制 class 类名(classList) 和 自定义属性(dataset)

    classList 用法: const div = document.querySelector('div') div.classList.add('myclass') // 添加类名 div.cla ...

  8. Bootstrap3基础 下载bootstrap3压缩包和相应的jQuery文件

      内容 参数   OS   Windows 10 x64   browser   Firefox 65.0.2   framework     Bootstrap 3.3.7   editor    ...

  9. ImportFileHandler 附件上传

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using LitJson; ...

  10. oracle 锁表

    select b.username,b.sid,b.serial#,logon_time from v$locked_object a,v$session b where a.session_id = ...