Scala 设置哈希码
假设我们在 Scala 中有三组字符串。一个有元素 A、B、C。二有元素 B、C、D。三有元素 J、K、I。
我的第一个问题是,有什么办法可以使这些集合中任意两个集合的哈希码相同吗? 我的第二个问题是,如果我将 D 添加到 One,将 A 添加到 Two 以获得新的集合 One.n 和 Two.n,One.n 和 Two.n 的哈希码是否相同?
Assume we have three sets of strings in Scala. One has elements A,B,C. Two has elements B,C,D. And Three has elements J,K,I.
My first question is, is there any way that the hashcodes for any two of these sets could be the same?
My second question is, if I add D to One and A to Two to get new Sets One.n and Two.n, are the hashcodes for One.n and Two.n the same?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题1)一般来说是的,完全有可能。哈希码的字节数有限。集合可以是任意大小。因此哈希码不能是唯一的(尽管通常是唯一的)。
问题2)为什么不尝试一下呢?
所以,是的,正如您所期望的那样,因为您希望
==
方法对于这两个实例都是 true。Question 1) In general yes, entirely possible. A hashcode is a limited number of bytes long. A Set can be any size. So hashcodes cannot be unique (although usually they are).
Question 2) Why not try it?
So, yes they are, as you might expect, since you would expect the
==
method to be true for these two instances.相等并且内部没有任何奇怪的东西(即任何具有不稳定哈希码的东西,或者哈希码与 equals 不一致的东西)应该具有相等的哈希码。如果这不是真的,并且集合是相同类型的集合,那么这是一个错误,应该报告。如果集合是不同类型的集合,则具有不同的哈希码可能是也可能不是错误(但无论如何它应该与 equals 一致)。然而,我不知道不同的集合实现不相等的任何情况(例如,即使可变的 BitSet 也与不可变的集合一致)。
因此:
Sets which are equal and don't have anything strange inside them (i.e. anything with an unstable hash code, or where the hash code is inconsistent with equals) should have equal hash codes. If this is not true, and the sets are the same type of set, it is a bug and should be reported. If the sets are different types of sets, it may or may not be a bug to have different hash codes (but in any case it should agree with equals). I am not aware of any cases where different set implementations are not equal (e.g. even mutable BitSet agrees with immutable Set), however.
So: