Java: external class for determining equivalence?

2019-04-23 15:43发布

问题:

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.

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.)

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.)

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

(Does Guava handle anything like this?)

回答1:

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

(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...)

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