首页 > 解决方案 > 不可变对哈希码

问题描述

我需要使用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

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

标签: javatupleshashcode

解决方案


正如在方法定义的注释中所指定的,这个实现是 的合约所必需的Map.Entry,它ImmutablePair实现了。


推荐阅读