Comparable和Comparator

目录

一、Comparable

二、Comparator 


Comparable和Comparator都表示对类型进行比较。但是Comparable表示的是某个类型本身具有比较的能力,而Comparator侧重于类型本身无比较能力,但是我们可以通过外部定义其可以通过某种规则进行比较。

一、Comparable

Comparable是接口,位于java.lang包中。JDK中对Comparable的描述: 

 * This interface imposes a total ordering on the objects of each class that
 * implements it.  This ordering is referred to as the class's <i>natural
 * ordering</i>
, and the class's <tt>compareTo</tt> method is referred to as
 * its <i>natural comparison method

即赋予实现该接口的类型本身具有比较能力。 

该接口提供的主要方法:

 public int compareTo(T o);

只有一个入参,强调的是传入的类型与this进行比较。

二、Comparator 

Comparator也是接口,但是位于java.util包中,JDK对其描述如下;

 * A comparison function, which imposes a <i>total ordering</i> on some
 * collection of objects.  Comparators can be passed to a sort method (such
 * as {@link Collections#sort(List,Comparator) Collections.sort} or {@link
 * Arrays#sort(Object[],Comparator) 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 {@link SortedSet sorted sets} or {@link
 * SortedMap sorted maps}), or to provide an ordering for collections of
 * objects that don't have a {@link Comparable natural ordering}
.

功能类似于Comparable,实现比较功能,但是更加侧重于对未实现Comparale接口的类型,即本身没有比较能力的 类型进行比较。

该接口提供的主要方法:

int compare(T o1, T o2);

有两个入参,实现的是传入的两个对象的比较,而不要求这两个对象本身具有比较能力。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值