Java: How to workaround the lack of Equatable interface?
Posted
by java.is.for.desktop
on Stack Overflow
See other posts from Stack Overflow
or by java.is.for.desktop
Published on 2010-06-18T13:14:29Z
Indexed on
2010/06/18
13:23 UTC
Read the original article
Hit count: 291
Hello, everyone!
As far as I know, things such as SortedMap
or SortedSet
, use compareTo
(rather than equals
) on Comparable<?>
types for checking equality (contains
, containsKey
).
But what if certain types are equatable by concept, but not comparable?
I have to declare a Comparator<?>
and override the method int compareTo(T o1, To2)
. OK, I can return 0 for instances which are considered equal. But, for unqeual instances, what do I return when an order is not evident?
Is the approach of using SortedMap or SortedSet on equatable but (by concept) not comparable types good anyway?
Thank you!
EDIT:
I don't want to store things sorted, but would I use "usual" Map and Set, I couldn't "override" the equality-behavior.
EDIT 2:
Why I can't just override equals(...)
: I need to alter the equality-behavior of a foreign class. Can't edit it.
EDIT 3:
Just think of .NET: They have IEquatable interface which cat alter the equality-behavior without touching the comparable behavior.
© Stack Overflow or respective owner