Java.util.Arrays 类

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

语法

public static int hashCode(Object[] a)

参数

a 指定数组,其内容要计算的基于内容的哈希代码。

返回值

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

异常

无。

示例:

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

import java.util.*;

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

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

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