Java.util.Arrays 类

java.util.Arrays.hashCode() 方法根据指定数组的内容返回哈希码。对于任意两个 int 数组 a 和 b,满足 Arrays.equals(a, b),也有 Arrays.hashCode(a) == Arrays.hashCode(b).

语法

public static int hashCode(int[] a)

参数

a 指定哈希值的数组要计算的值。

返回值

返回数组的基于内容的哈希代码。

异常

不适用。

示例:

在下面的示例中,java.util.Arrays.hashCode() 方法用于检查两个 int 数组是否相等。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建三个int数组
    int Arr1[] = {10, 5, 25};
    int Arr2[] = {10, 5, 25};
    int Arr3[] = {10, -5, -25};

    //打印数组的哈希码
    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)); 


    //检查Arr1和Arr2是否相等
    boolean check = (Arrays.hashCode(Arr1) == Arrays.hashCode(Arr2));
    System.out.println("\nAre Arr1 and Arr2 equal?: "+ check);  

    //检查Arr1和Arr3是否相等
    check = (Arrays.hashCode(Arr1) == Arrays.hashCode(Arr3));
    System.out.println("Are Arr1 and Arr3 equal?: "+ check);  
  }
}

上述代码的输出将是:

hashCode of Arr1: 39581
hashCode of Arr2: 39581
hashCode of Arr3: 39221

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