java Comparable and Comparator
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的更多相关文章
- Java Comparable和Comparator
Java中在进行数据排序时,Comparable和Comparator不可缺少会遇得到.普通的String.Integer等类型,已经实现了Comparable接口,而有些时候,我们须要对一些其它不存 ...
- Java Comparable 和 Comparator 接口详解
本文基于 JDK8 分析 Comparable Comparable 接口位于 java.lang 包下,Comparable 接口下有一个 compareTo 方法,称为自然比较方法.一个类只要实现 ...
- java Comparable 和 Comparator接口区别
Comparable 简介 Comparable 是排序接口. 若一个类实现了Comparable接口,就意味着“该类支持排序”. 即然实现Comparable接口的类支持排序,假设现在存在“实现C ...
- Java Comparable与Comparator区别
1,两种接口的展示 下面的程序是两个类各自实现了Comparable接口.Comparator接口 package com.cnblogs.mufasa.Solution; import java.u ...
- Java comparable 和 comparator
一.comparator 接口继承 public class ComparatorTest { /** * @param args */ public static void main(String[ ...
- Java中Comparable与Comparator的区别
相同 Comparable和Comparator都是用来实现对象的比较.排序 要想对象比较.排序,都需要实现Comparable或Comparator接口 Comparable和Comparator都 ...
- Java中Comparable和Comparator接口区别分析
Java中Comparable和Comparator接口区别分析 来源:码农网 | 时间:2015-03-16 10:25:20 | 阅读数:8902 [导读] 本文要来详细分析一下Java中Comp ...
- Java中Comparable和Comparator区别小结
一.Comparable简介 Comparable是排序接口.若一个类实现了Comparable接口,就意味着该类支持排序.实现了Comparable接口的类的对象的列表或数组可以通过Collecti ...
- Java 中 Comparable 和 Comparator 比较
Java 中 Comparable 和 Comparator 比较 目录: Comparable Comparator Comparable 和 Comparator比较 第二个例子 之 Compar ...
随机推荐
- sitecore8.2 基于相对路径查询item
当前项目: bar (path: /sitecore/content/home/foo/bar) 查询: query:./child/grandchild 结果: grandchild (path: ...
- what?iView的DropDown没有element的split-button?提issure?等不及了,自己实现一个
开始正文之前,有必要先说自己实现这个组件的必要性描述. 话说大家做表格时,增删查改按钮都是放在哪里的?最简单的方式应该是这样: 是不是感觉奇丑无比啊,于是改成了这样: 但是这种操作按钮一多后就没位置放 ...
- Web Deploy 发布网站错误 检查授权和委派设置
Web Deploy发布ASP.NET网站给我们提供方便,配置好后可以很方便地发布网站到IIS服务器. 自安装Web Deploy一年以来,一直都用得好好地. 直到最近,Gitlab-CI自动发布出了 ...
- tomcat服务器1
1.在访问servlet时,一定要引入servlet-api.jar包 此包在Tomcat解压文件夹的lib子目录中,复制此包到Eclipse中的项目中WEB-INF的lib中,再右击Build Pa ...
- 【shell】awk按域去除重复行
首先解释一下什么叫“按域去除重复行”: 有的时候我们需要去除的重复行并不是整行都重复,两行的其中一列的元素相同我们有的时候就需要认定这两行重复,因此有了今天的内容. 去除重复行shell有一个原生命令 ...
- composer安装doctrine/dbal
composer安装doctrine/dbal composer安装doctrine/dbal,安装不成功,使用的安装命令为官方提供命令“composer require doctrine/dbal” ...
- 自定义控件之SegmentControlView
SegmentControlView配合PageView使用 效果图 核心代码 package com.example.segmentcontrolview; import android.conte ...
- [C++ Primer Plus] 第9章、内存模型和名称空间(一)程序清单
程序清单9.9(静态存储连续性.无链接性) #include<iostream> using namespace std; ; void strcount(const char *str) ...
- Java基础学习-流程控制语句
在一个程序执行的过程中,各条语句的执行顺序对程序的结果是有直接影响的.也就是说程序的流程对运行结果有直接的影响.所以,我们必须清楚每条语句的执行流程.而且,很多时候我们要通过控制语句的执行顺序来实现我 ...
- html是什么?一个完整的html代码告诉你(完整实例版)
html什么意思?这篇文章主要为大家仔细的解释了HTML文档的一个基础的完整代码,还有具体的实例解释,让大家能一下就看懂HTML的基础结构和用法.下面我们一起来看看吧一.html是什么?点击查看htm ...