Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Comparable so it is consistent with identity-equality

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.

like image 841
Balz Guenat Avatar asked Apr 01 '19 08:04

Balz Guenat


People also ask

What does it mean to implement comparable?

The fact that a class implements Comparable means that you can take two objects from that class and compare them.

Can we implement comparable interface?

We can implement the Comparable interface with the Movie class, and we override the method compareTo() of Comparable interface.


1 Answers

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.

like image 120
GhostCat Avatar answered Sep 19 '22 14:09

GhostCat