0

Suppose I want to create a HashSet or a HashMap whose keys are arrays of primitive types, like below:

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

What hash codes these structures will be using for the arrays?

I know that the root class Object contains hashCode() and it is therefore may be used for instances of any inherited class (in which it may be overridden or not). The Arrays class has a 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" chapter in JLS doesn't clarifies the situation either.

John McClane
  • 3,498
  • 3
  • 12
  • 33
  • 1
    this is a couple lines of code to test it, why do you even ask here? – user2023577 Jun 28 '19 at 22:31
  • 2
    @user2023577 It is not a good practice to rely on a local test because implementation may change from time to time and from device to device. I need an authoritative source to rely upon. Besides that, there are also arrays of non-primitive types. I cannot test them all. – John McClane Jun 28 '19 at 22:34
  • 4
    The hash code is the identity-based hash code inherited from object. It is not based on values in the array. – Andy Turner Jun 28 '19 at 22:36
  • > "It is not a good practice to rely on a local test". If there is a contract on arrays hashcode, you could rely on predictable values between runs/instances. Only one result differing and you know it's not a contract. – user2023577 Jun 28 '19 at 22:37

1 Answers1

5

Arrays do have hashCode, per JLS 10.7 (emphasis added):

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.

This means that hashCode is inherited from Object, and thus is identity-based, and not dependent upon the values in the array.

This might be what you want, but I suggest it might not be. If you want a hash code based on values in an array, you would need to wrap the array in some class which implements a sensible equals and hash code.

Community
  • 1
  • 1
Andy Turner
  • 137,514
  • 11
  • 162
  • 243