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. Angular4 投影ngContent

  2. MariaDB导入XXX.sql文件

    使用的 MariaDB5.5.52 开启数据库服务: systemctl start mariadb 要使用该脚本,登录数据, mysql -u root -p 根据提示输入你安装数据库时需设置密码, ...

  3. C博客作业05--指针

    1. 本章学习总结 1.1 思维导图 1.2 本章学习体会及代码量学习体会 1.2.1 学习体会 这几周学习了指针,指针是C语言的一个重要的概念,也是特色之一.它可以通过对地址的访问来改变值,所以它的 ...

  4. 问题 1923: [蓝桥杯][算法提高VIP]学霸的迷宫 (BFS)

    题目链接:https://www.dotcpp.com/oj/problem1923.html 题目描述 学霸抢走了大家的作业,班长为了帮同学们找回作业,决定去找学霸决斗.但学霸为了不要别人打扰,住在 ...

  5. pandas的基本功能(一)

    第16天pandas的基本功能(一) 灵活的二进制操作 体现在2个方面 支持一维和二维之间的广播 支持缺失值数据处理 四则运算支持广播 +add - sub *mul /div divmod()分区和 ...

  6. jsp页面在Android系统和ISO系统的兼容性问题

    问题:一个jsp页面在Android手机上显示正常,但到了ISO系统上jsp页面的样式不显示了. 原因:css文件中设置样式时单位不兼容. 解决方案:将rem 转换成px;

  7. ORA-00338

    dg环境从库报错:ORA-00338: log 5 of thread 1 is more recent than control fileORA-00312: online log 5 thread ...

  8. FL Studio中音频ASIO4ALL的设置

    上期我们讲解了FL Studio中音频的相关设置,今天我们来进一步讲解音频设置中的ASIO4ALL的设置,FL Studio安装包括FL Studio ASIO和第三方ASIO驱动程序ASIO4ALL ...

  9. 浅谈Vue之双向绑定

    VUE实现双向数据绑定的原理就是利用了 Object.defineProperty() 这个方法重新定义了对象获取属性值(get)和设置属性值(set)的操作来实现的.那么Object.defineP ...

  10. AutoCAD2015有时候会显示乱七八糟的线

    问题描述:AutoCAD2015以上版本有时候打开一张图,会出现乱七八糟的线 解决方案: 这是由于硬件加速平滑线显示引起的,可以如下修改