java - 不可变对哈希码
问题描述
我需要使用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
这对我来说似乎很奇怪。有人可以解释这样做的合理性是什么吗?
解决方案
正如在方法定义的注释中所指定的,这个实现是 的合约所必需的Map.Entry
,它ImmutablePair
实现了。
推荐阅读
- .net-core - Asp net core IdentityServer4 GetValidTwoFactorProvidersAsync 返回 null
- python - 如何绘制来自 for 循环的结果图
- sql - WHERE 子句匹配或为空
- wordpress - Woocommerce - 如何在循环产品缩略图中添加一个“添加到购物车”链接?
- go - 如何获得最大打开文件句柄的软限制
- android - 从数据库重新填充 EditTexts 的最佳方法
- python - 一段时间后在库存中添加一个项目,discord.py
- javascript - 获取时间格式为 hh:mm
- json - 将 JSON 解组为 Map 结构
- python-3.x - 迁移到 python 3.6 后的 Django UnicodeDecodeError