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
2
  • That's the Object#hashCode() implementation. Commented Sep 28, 2013 at 18:36
  • 1
    Use Arrays.hashCode(Object[] a) or Arrays.deepHashCode(Object[] a). Commented Sep 28, 2013 at 18:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments