【发布时间】: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.hashCodedocumentation,It 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 知道了。是的,我认为现在这很有意义