Java:确定等效性的外部类? [英] Java: external class for determining equivalence?

查看:90
本文介绍了Java:确定等效性的外部类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java具有 Comparator<T> 用于提供类本身外部对象的比较,以允许使用多种/替代方法进行有序比较.

Java has a Comparator<T> for providing comparison of objects external to the class itself, to allow for multiple/alternate methods of doing ordered comparisons.

但是进行无序比较的唯一标准方法是在一个类中覆盖equals() .

But the only standard way of doing unordered comparisons is to override equals() within a class.

当我想在类外部提供多个/替代无序比较时应该怎么做?(明显的用例是根据特定属性将集合划分为等效类.)

What should I do when I want to provide multiple/alternate unordered comparisons external to a class? (Obvious use case is partitioning a collection into equivalence classes based on particular properties.)

假定最终用途是无序检查(例如,不是用于排序或索引编制),是否可以实现只检查相等性的Comparator<T>,如果两个对象相等,则返回0,当两个对象相等时,返回值= 0两个物体不相等? (注释:我不采用此解决方案的唯一原因是,从技术上讲,它可以通过不提供满足可传递性和对称性的关系来破坏Comparator的约定.)

Assuming the end use is for unordered checking (e.g. not for sorting or indexing), is it ever OK to implement Comparator<T> that just checks for equality, returning 0 if two objects are equal, and a value != 0 when two objects are unequal? (note: the only reason I don't jump on this solution, is that technically it can break the contract for Comparator by not providing a relation that satisfies transitivity and symmetry.)

似乎应该有一个EqualsComparator<T>标准类之类.

It seems like there should have been an EqualsComparator<T> standard class or something.

(番石榴会处理这样的事情吗?)

(Does Guava handle anything like this?)

推荐答案

是的,Guava具有

Yes, Guava has the Equivalence interface and the Equivalences class (Removed in Guava release 14.0).

(是的,这是 很有用的东西,可悲的是Java中缺少它.我们真的应该为此选择HashMapHashSet等...)

(And yes, it's something which is very useful and sadly lacking in Java. We really should have options around this for HashMap, HashSet etc...)

虽然在某些情况下Comparator<T> 可以,但是它没有提供hashCode方法,该方法对于基于散列的集合非常重要.

While Comparator<T> may be okay in some situations, it doesn't provide the hashCode method which would be important for hash-based collections.

这篇关于Java:确定等效性的外部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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