25

What is the Java equivalent of .NET's IEquatable Interface?

Tim Bender
  • 20,112
  • 2
  • 49
  • 58
Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447

4 Answers4

21

Unfortunately I don't believe there is one - which is a pain in terms of providing hash maps etc with custom equality comparisons :(

Obviously there's Comparable<T> as an equivalent to IComparable<T> and Comparator<T> for IComparer<T>, but I don't believe there's any equivalent of IEqualityComparer<T> and IEquatable<T>.

There may be third party libraries providing the same sort of interface and maps which use them of course...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • It wouldn't be that much of a stretch to create a delegating decorator which implements `Map` and your own `Equatable` (*is that even a word?*) interface though. – Esko Jul 12 '10 at 11:12
  • @Esko: Do you mean making the underlying map contain proxied keys, effectively? It's doable, but it would be ugly... and I suspect it would create issues when you tried to do weak maps etc. It would have been much nicer if it had been in there to start with. – Jon Skeet Jul 12 '10 at 13:40
  • Why not that way too. Proxying through `WeakReference` shouldn't be that much of an extra work, either. I do see your point though, C# has lots of these things readily implemented while Java likes to be the "barebones" language. I guess Google Collections may have something for this through its Predicate/Function system but I'm not sure... – Esko Jul 12 '10 at 14:44
  • @Esko: I don't believe I've seen any Google collections with the `IEqualityComparer` interface equivalent, which is really what's required for the most general purpose solution. (It's easy to build a comparer based on an equatable type.) – Jon Skeet Jul 12 '10 at 14:49
  • 2
    The lack of an Equatable interface in the BCL is one of Java's many frustrating flaws - it essentially requires that you implement (or at least imply that you implement) a total order for a class even when it may not make any sense just to allow a type to be used as a key in a hashmap. – LBushkin Nov 30 '13 at 18:29
9

If you are just looking for that interface to implement the equals() method, you can override the object.equals() method directly.

sra
  • 23,820
  • 7
  • 55
  • 89
  • 3
    a good override implementation of `equals()` can be found here: http://stackoverflow.com/questions/185937/overriding-the-java-equals-method-quirk – Julien Feb 21 '13 at 09:15
2

The IEquatable<T> interface is primarily useful with generic classes that store many instances of what may be unboxed structure types; it's marginally useful with sealed types, and worse than useless with unsealed types. There's thus really wouldn't be any point to implementing IEquatable<T> in Java.

supercat
  • 77,689
  • 9
  • 166
  • 211
1

There's an equivalent type in Guava called Equivalence<T>.

Craig Gidney
  • 17,763
  • 5
  • 68
  • 136