Does it make sense for peers and compare to be inconsistent?

I want to create a class that can be used in SortedSet | SortedMap .

 class MyClass implements Comparable<MyClass>{ // the only thing relevant to comparisons: private final String name; //... } 

Class instances must be sorted by their name. However, I do not want equally named instances to be considered equal.

So, the contents of the SortedSet will look like a, a, a, b, c .
(Normally, a SortedSet only allows a, b, c )

First of all: is it (philosophically) consistent?

If so, should I expect unpredictable behavior when I do not override equals(...) and hashCode() ?

Edit:
Sorry, my question seems inconsistent:
I want to put several "equal" values inside the set , which does not allow this by concept.
Therefore, please do not answer my question. Thanks to everyone who has already answered.

+7
java collections
source share
4 answers

Let me ask you a question: does it make sense to have a.compareTo(b) return 0 and a.equals(b) return false ?

Instead, I would use Comparator<MyClass> . That's why all the SortedMap / SortedSet implementations that I know of allow you to go through Comparator when you create it.

+18
source share

From Javadoc to Compare

It is strongly recommended (although not required) that natural orders be consistent with equalities. This is so because sorted sets (and sorted cards) without explicit comparators behave β€œ weirdly ” when they are used with elements (or keys), natural ordering is incompatible with equal

If you want to have compareTo incompatible with equals (), it is recommended that you use an explicit comparator instead, providing a class that implements Comparator.

If so, should I expect unpredictable behavior when I don't override equals (...) and hashcode ()?

You still have to override equals () and hashcode (). Regardless of whether equals () and hashcode () are compatible with compareTo, this is another matter.

+4
source share

Effective Java recommends that if you do not implement compareTo matching equals , you should clearly state:

Recommended language: "Note: This class has a natural order that is incompatible with peers."

+2
source share

Just put this code in the equals method and don’t think about it anymore:

 public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof MyClass)) return false; return 0 == this.compareTo((MyClass) obj); } 
0
source share

All Articles