I have a class for which equality (as per equals()
) must be defined by the object identity, i.e. this == other
.
I want to implement Comparable
to order such objects (say by some getName()
property). To be consistent with equals()
, compareTo()
must not return 0
, even if two objects have the same name.
Is there a way to compare object identities in the sense of compareTo
? I could compare System.identityHashCode(o)
, but that would still return 0
in case of hash collisions.
The fact that a class implements Comparable means that you can take two objects from that class and compare them.
We can implement the Comparable interface with the Movie class, and we override the method compareTo() of Comparable interface.
I think the real answer here is: don't implement Comparable then. Implementing this interface implies that your objects have a natural order. Things that are "equal" should be in the same place when you follow up that thought.
If at all, you should use a custom comparator ... but even that doesn't make much sense. If the thing that defines a < b ... is not allowed to give you a == b (when a and b are "equal" according to your < relation), then the whole approach of comparing is broken for your use case.
In other words: just because you can put code into a class that "somehow" results in what you want ... doesn't make it a good idea to do so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With