本文介绍了对于equals和compareTo是否有意义是不一致的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让一个类在 SortedSet |中可用 SortedMap

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.

code> SortedSet 内容将类似于 a,a,a,b,c

(通常, SortedSet 只允许 a,b,c

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?

如果是这样,我不得不指望不可预测的行为,当我不
覆盖等于(...) hashCode()

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



对不起,我的问题似乎不一致:

我要在设置中添加多个 / strong>,这不允许这个
的概念。

所以,请不要回复我的问题。

感谢所有已经回复。


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

推荐答案

让我问一个问题: a.compareTo(b) return 0 and a.equals(b) return false

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

我会使用。这就是为什么所有 SortedMap / SortedSet 我知道的实现允许你传递 Comparator

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.

这篇关于对于equals和compareTo是否有意义是不一致的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 15:53