为什么比较器声明等于? [英] Why does Comparator declare equals?

查看:102
本文介绍了为什么比较器声明等于?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Comparator接口有自己的 equals()方法。默认情况下,任何类都将通过Object类获得 equals()。在接口内有什么需要 equals()方法?

The Comparator interface has its own equals() method. Any class will get equals() by default through Object class. What is the need to have equals() method inside an interface?

推荐答案

比较器优化 Object.equals 的合约:它必须满足<$ c $设定的约束c> Object.equals 然后一些

Comparator refines the contract of Object.equals: It has to satisfy the constraints set out by Object.equals and then some.


此外,此方法可以仅当指定的对象也是比较器并且它与此比较器施加相同的顺序时才返回true。因此, comp1.equals(comp2)意味着 sgn(comp1.compare(o1,o2))== sgn(comp2.compare(o1, o2))为每个对象引用 o1 o2

Additionally, this method can return true only if the specified object is also a comparator and it imposes the same ordering as this comparator. Thus, comp1.equals(comp2) implies that sgn(comp1.compare(o1, o2))==sgn(comp2.compare(o1, o2)) for every object reference o1 and o2.

比较器中声明等于允许你以javadoc的形式记录下来。

Declaring an equals inside Comparator allows you to document this in the form of javadoc.

请注意,API的文档也可作为合同,因此这里不仅仅是化妆品。这是其他代码和代码可以依赖的显式约束。

Note that the documentation of the API also serves as the contract, so it's not just cosmetics here. It's explicit constraints that other code and your code can rely on.

在类似情况下,如果您的方法较少,它也可以用作记录意图。即, Interface.method 应该存在,无论其超级接口如何发展。

In similar situations where you have less established methods, it may also serve as documenting an intent. I.e., Interface.method should be there, regardless of how its super interfaces evolves.

这篇关于为什么比较器声明等于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆