gpt4 book ai didi

java - 数组有固有的 hashCode() 吗?

转载 作者:行者123 更新时间:2023-12-01 07:44:22 25 4
gpt4 key购买 nike

假设我想创建一个HashSetHashMap其键是原始类型的数组,如下所示:

Set<int[]> setOfIntArrays = new HashSet<>();
Map<char[], String> mapOfCharArrays = new HashMap<>();

这些结构将用于数组的哈希码是什么?

我知道根类 Object包含hashCode()因此它可以用于任何继承类的实例(其中它可以被覆盖或不被覆盖)。 Arrays类有一个 bunch静态hashCode(...)所有基本类型数组的方法。这些方法是否也“内置”为基本类型数组的(重写)实例方法?由于数组充当集合和映射中的普通类,因此似乎是合乎逻辑的。但是,没有针对类 int[] 的 javadoc。和 "Arrays" JLS 中的章节也没有澄清这种情况。

最佳答案

数组确实有hashCode,根据JLS 10.7 (强调):

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.

  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

  • A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

这意味着 hashCode 继承自 Object,因此是基于身份的,而不依赖于数组中的值。

可能是您想要的,但我建议它可能不是。如果您想要基于数组中的值的哈希码,则需要将数组包装在某个实现合理的等于和哈希码的类中。

关于java - 数组有固有的 hashCode() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56813729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com