【问题标题】:ImmutablePair Hashcode不可变对哈希码
【发布时间】:2021-09-05 10:27:36
【问题描述】:

我需要使用ImmutablePair。但似乎它的哈希码是这样定义的:https://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/tuple/Pair.html#line.208。这意味着ImmutablePair.of("a", "a")ImmutablePair.of("b", "b") 将具有相同的hashCode 0

ImmutablePair<String, String> p1 = ImmutablePair.of("a", "a");
System.out.println("Pair 1 hashcode: " + p1.hashCode());
ImmutablePair<String, String> p2 = ImmutablePair.of("b", "b");
System.out.println("Pair 2 hashcode: " + p2.hashCode());

输出:

Pair 1 hashcode: 0
Pair 2 hashcode: 0

这对我来说似乎很奇怪。有人能解释一下这样做的合理性是什么吗?

【问题讨论】:

  • 你的意思是这一行哈希码遵循{@code Map.Entry}中的定义吗?
  • 是的。这正是我的意思。
  • 如果 2 个不同的条目返回相同的哈希码,假设的问题是什么?
  • @Psidom 那个警告/投诉是完全错误的。根据Java的Object.hashCode documentationIt is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results.
  • @fps 知道了。是的,我认为现在这很有意义

标签: java tuples hashcode


【解决方案1】:

正如方法定义的注释中所指定的,此实现是Map.Entry 的合约所要求的,ImmutablePair 实现了该合约。

【讨论】:

  • 你能扩展一下 Map.Entry 的合同需要这个实现 吗?我不太确定我明白这意味着什么。
  • 任何实现Map.Entry的类都需要按照接口指定的方式实现hashCode。这就是...接口在 Java 中的一般工作方式:它们指定所需的行为。
  • 好的,我看到Map.Entry 有一个类似的实现:docs.oracle.com/javase/8/docs/api/java/util/Map.Entry.html。你有任何参考为什么它必须以这种方式实现以保证e1.equals(e2) =&gt; e1.hashCode() == e2.hasCode()
  • Map.Entry 不必选择那个实现,但它确实选择了,任何实现它的东西都必须以同样的方式做。
  • @Psidom 因为如果将其转换为 Map.Entry,它的行为必须与所有 Map.Entry 完全相同,包括具有匹配的哈希码。实现这个接口可能是人为的,但它确实实现了,所以它必须遵循要求。
猜你喜欢
  • 1970-01-01
  • 2016-01-11
  • 2020-06-07
  • 1970-01-01
  • 2016-03-10
  • 2013-12-11
  • 2018-04-04
  • 1970-01-01
  • 2012-09-16
相关资源
最近更新 更多