比较器最佳实践 [英] Comparator best practice

查看:122
本文介绍了比较器最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我实施自定义比较器,除了比较,> b $ b另外还有一个比较器的定义合同?

If I implement a custom comparator is it considered good practice to overide equals besides compare?
Additionally is there a defined contract for a Comparator?

推荐答案

Comparator的合约在其javadoc >。特别是:

The contract of Comparator is defined in its javadoc. In particular:


使用比较器时应谨慎,比较器可以强制使用与equals不一致的顺序来排序排序集合)。假设具有显式比较器c的排序集合(或排序映射)与从集合S中绘制的元素(或键)一起使用。如果c对S施加的排序与equals不一致,则排序集合(或排序映射)将表现奇怪。特别是,排序的集合(或排序的映射)将违反set(或map)的一般合同,它以等于定义。

Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals.

通常,如果两个对象从等于透视相等,而不是从 compareTo 透视,两个对象作为TreeMap中的键。这可能导致不直观的行为。也可以在特定情况下进行。

Typically, if 2 objects are equal from an equals perspective but not from a compareTo perspective, you can store both objects as keys in a TreeMap. This can lead to un-intuitive behaviour. It can also be done on purpose in specific situations.

例如,此answer 显示了一个示例,其中希望equals和compareTo不一致

For example, this answer shows an example where it is desirable that equals and compareTo be inconsistent.

这篇关于比较器最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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