数组是否具有固有的 hashCode()?

Do arrays have inherent hashCode()?

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

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

这些结构将用于数组的散列码是什么?

我知道根 class Object 包含 hashCode() 因此它可以用于任何继承 class 的实例(其中它可以被覆盖或不)。 Arrays class 在 JLS 中有一章 bunch of static hashCode(...) methods for arrays of all primitive types. Are these methods also "built-in" as (overridden) instance methods of arrays of primitive types? Since arrays act as ordinary classes in collections and maps, it seems logical to be so. However, there is no javadoc for, say, class int[] and the "Arrays" 也没有说明情况。

数组确实有 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,因此是 identity-based,并且不依赖于数组中的值。

可能是您想要的,但我认为它可能不是。如果你想要一个基于数组中值的哈希码,你需要将数组包装在一些 class 中,它实现了一个合理的等号和哈希码。