java 中 `hashmap` 默认使用对象的 `equals()` 和 `hashcode()` 判断键的相等性;而 `int[]` 数组继承自 `object`,其 `equals()` 比较的是引用而非内容,导致相同元素的两个数组被视为不同键,从而查不到值。
在 Java 中,HashMap
然而,原始类型数组(如 int[])并未重写 equals() 和 hashCode() 方法,而是直接使用 Object 的默认实现:
因此,以下代码始终返回 false:
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a.equals(b)); // false —— 内容相同,但引用不同
System.out.println(a.hashCode() == b.hashCode()); // 极大概率 false这正是问题的根本原因:
✅ 正确解决方案(推荐):改用不可变、语义相等的键类型
Map, int[]> coloursMap = new HashMap<>(); // 存储 coloursMap.put(Arrays.asList(i, j, k), new int[]{1, 2, 3}); // 查询(自动按元素值比较) int[] result = coloursMap.get(Arrays.asList(i, j, k)); // ✅ 正确返回
✅ 优势:Arrays.asList() 返回的 List 正确实现 equals()/hashCode();Integer 包装类也满足契约。 ⚠️ 注意:避免使用 Arrays.asList(new int[]{...})(会将整个数组视为单个元素),务必传入拆箱后的 Integer 值。
public final class Coord {
public final int x, y, z;
public Coord(int x, int y, int z) { this.x = x; this.y = y; this.z = z; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Coord coord = (Coord) o;
return x == coord.x && y == coord.y && z == coord.z;
}
@Override
public int hashCode() {
return Objects.hash(x, y, z); // 自动处理 null 安全与一致性
}
}
// 使用
Map coloursMap = new HashMap<>();
coloursMap.put(new Coord(i, j, k), new int[]{1, 2, 3});
int[] result = coloursMap.get(new Coord(i, j, k)); // ✅ 高效且语义清晰 若坚持用 int[],可借助 Arrays.equals() 和 Arrays.hashCode(),但需包装为自定义键或使用 IdentityHashMap 不适用(因 IdentityHashMap 仍按引用比较)。更稳妥的方式是封装:
// ❌ 错误:不能直接用 int[] 作键
// ✅ 可行但冗余:每次查询前手动遍历(O(n) 性能差,仅作说明)
int[] target = {i, j, k};
return coloursMap.entrySet().stream()
.filter(e -> Arrays.equals(e.getKey(), target))
.map(Map.Entry::getValue)
.findFirst()
.orElse(null);? 关键总结: