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

1 Answers1

2

Because array hashcode does the same as Object's hash code.

And since you array is always the same object the hash code will be the same.

luiso1979
  • 868
  • 1
  • 6
  • 18