Does it make sense for equals and compareTo to be inconsistent?

Does it make sense for equals and compareTo to be inconsistent?

归属感 发布于 2021-11-24 字数 1077 浏览 777 回复 4 原文

I want to make a class usable in SortedSet | SortedMap.

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

  //...
}

The class' instances must be sorted by their name property.
However, I don't want equally named instances to be considered as equal.

So a SortedSet content would look like a, a, a, b, c.
(Normally, SortedSet would only allow a, b, c)

First of all: is this (philosophically) consistent?

If so, do I have to expect unpredictable behavior, when I don't
override equals(...) and hashCode()?

Edit:
I am sorry, my question seems inconsistent:
I want to put multiple "equal" values inside a set, which doesn't allow this
by concept.
So, please don't reply to my question anymore.
Thanks to all who already replied.

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

扫码加入群聊

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

末が日狂欢 2022-06-07 4 楼

Just put this code in the equals method and dont ever think about it again:

public boolean equals(Object obj) {
    if (this == obj) return true;
    if (!(obj instanceof MyClass)) return false;
    return 0 == this.compareTo((MyClass) obj);
}
柠北森屋 2022-06-07 3 楼

Effective Java recommends that if you don't implement compareTo consistent with equals you should clearly indicate so:

The recommended language is "Note:
This class has a natural ordering that
is inconsistent with equals."

眼眸印温柔 2022-06-07 2 楼

From the Javadoc for Comparable

It is strongly recommended (though not
required) that natural orderings be
consistent with equals. This is so
because sorted sets (and sorted maps)
without explicit comparators behave
"strangely" when they are used with
elements (or keys) whose natural
ordering is inconsistent with equals

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

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

You should still override equals() and hashcode(). Whether or not equals() and hashcode() are consistent with compareTo is a different matter.

淡淡绿茶香 2022-06-07 1 楼

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

I would use a Comparator<MyClass> instead. This is why all SortedMap/SortedSet implementations that I know of allow you to pass in a Comparator at creation.