0

I wrote the following code that verifies that an array of characters in java always returns the same hashcode irrespective of what the array contains.

Isn't this a flawed implementation? And how is the hashcode calculated for the array when it is independant of what the array contains?

import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;

class Main{ 

    public static void main(String[] args)throws java.lang.Exception{
        char[] arr = new char[10];
        Random rand = new Random(1);
        for(int i=0; i<10; i++){
            for(int j=0; j<arr.length; j++){
                arr[j] = (char)('a' + rand.nextInt(26));
            }
            printArr(arr);
            System.out.println(" " + arr.hashCode());
        }
    }

    private static void printArr(char[] a){
        for(Character c : a){
            System.out.print(c);
        }
    }
}

Output :

rahjmyuwwk 1169863946
rxnfmqgeeb 1169863946
eoapezsdzs 1169863946
pmqcxjtgdy 1169863946
xkrpvmwmmp 1169863946
mpylwrkvme 1169863946
ozgboqayhu 1169863946
fojcmxghpt 1169863946
eqrgfnzdjs 1169863946
jggwxhtnsk 1169863946
4

1 回答 1

2

因为数组 hashcode 和 Object 的 hash code 是一样的。

而且由于您的数组始终是同一个对象,因此哈希码将是相同的。

于 2013-09-28T18:37:59.860 回答