In Java, Arrays.hashCode(a) returns an int calculated from the elements of a. Two arrays for which Arrays.equals returns true always get the same hash code.
The array's own a.hashCode() is based on the object's identity, so two arrays with the same numbers usually get different values. Arrays.hashCode is the content-based version you need when an array is part of a hashCode() method or a hash-based key.
A static method of java.util.Arrays (Java 5+): call it on the class, as in Arrays.hashCode(...); there is no Arrays object to create.
Syntax
Pass the array; the result depends only on its elements and their order.
Java
int[] a = {1, 2, 3};
int h = Arrays.hashCode(a); // 30817
Arrays.hashCode(new int[] {1, 2, 3}); // 30817 again
Arrays.hashCode(new int[0]); // 1
Arrays.hashCode((int[]) null); // 0
Call
What it does
Arrays.hashCode(int[] a)
Hash of the values; same overload for every primitive type.
Arrays.hashCode(Object[] a)
Uses each element's own hashCode(); null elements count as 0.
Objects.hash(x, y, z)
Shortcut that wraps the values in an array and calls Arrays.hashCode.
return Arrays.hashCode(values);
Typical line inside a class's hashCode() method.
The algorithm starts at 1 and, for each element, computes result = 31 * result + elementHash. For int the element hash is the value itself; for other types it is the matching wrapper's hash (for example Long.hashCode or Boolean.hashCode). For int[] the result equals the hash code of a List<Integer> with the same elements.
Library declarations
Java
// java.util.Arrays (since Java 5)
public static int hashCode(int[] a)
public static int hashCode(long[] a)
public static int hashCode(double[] a)
public static int hashCode(boolean[] a)
public static int hashCode(Object[] a)
// also short[], char[], byte[], float[]
Parameters
Parameter
Description
a
The array whose contents are hashed. May be null.
Return Value
Return Value
Description
int
A content-based hash code; 1 for an empty array and 0 for null.