tags:

views:

90

answers:

2

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

+3  A: 

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
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
@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
@Jon: 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
@Esko: I don't believe I've seen any Google collections with the `IEqualityComparer<T>` 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
A: 

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

Ahmed Mostafa