Java Utility Library

Java Arrays - hashCode() Method



The java.util.Arrays.hashCode() method returns a hash code based on the contents of the specified array. For any two double arrays a and b such that Arrays.equals(a, b), it is also the case that Arrays.hashCode(a) == Arrays.hashCode(b).

Syntax

public static int hashCode(double[] a)

Parameters

a Specify the array whose hash value to compute.

Return Value

Returns a content-based hash code for the array.

Exception

NA.

Example:

In the example below, the java.util.Arrays.hashCode() method is used to check whether the two arrays of doubles are equal or not.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating three double arrays
    double Arr1[] = {10.1, 5.2, 25.3};
    double Arr2[] = {10.1, 5.2, 25.3};
    double Arr3[] = {10.1, 20.2, 30.3};

    //print the hash code of arrays
    System.out.println("hashCode of Arr1: "+ Arrays.hashCode(Arr1)); 
    System.out.println("hashCode of Arr2: "+ Arrays.hashCode(Arr2)); 
    System.out.println("hashCode of Arr3: "+ Arrays.hashCode(Arr3)); 


    //check Arr1 and Arr2 for equality
    boolean check = (Arrays.hashCode(Arr1) == Arrays.hashCode(Arr2));
    System.out.println("\nAre Arr1 and Arr2 equal?: "+ check);  

    //check Arr1 and Arr3 for equality
    check = (Arrays.hashCode(Arr1) == Arrays.hashCode(Arr3));
    System.out.println("Are Arr1 and Arr3 equal?: "+ check);  
  }
}

The output of the above code will be:

hashCode of Arr1: -1535839105
hashCode of Arr2: -1535839105
hashCode of Arr3: -2078084000

Are Arr1 and Arr2 equal?: true
Are Arr1 and Arr3 equal?: false

❮ Java.util - Arrays