Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: external class for determining equivalence?

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

like image 897
Jason S Avatar asked Aug 31 '11 15:08

Jason S


1 Answers

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.

like image 67
Jon Skeet Avatar answered Nov 07 '22 22:11

Jon Skeet