Best way to define a hashcode method for char array

1.4k views Asked by At

Best way to define a hashcode method for char array. Is there a better way to implement our own hascode() method for minimum collision?

char arr1[]={'a','b','c'};
char arr2[]={'b','a','c'};
char arr3[]={'c','a','b'};

int hashcode() {
   int p=31;
   int n=arr1.length;
   int hash=1;
   for(int i=0;i<n;i++) {
       hash=31*hash+(int)arr1[i];
   }
   return hash;
}
2

There are 2 answers

0
vmrvictor On

If you have an object that contains an array of chars and you want to override the hashCode() then you can use the method for It:

java.util.Arrays.hashCode()
0
Stefan Steinegger On

It depends very much on how your data is typically different from each other.

You may write this hash code function:

return arr.Length;

And it could perfectly fit if most of your arrays have a different size.

Or you may use the first two items if your array has typically completely different content.

Note: it doesn't make sense to loop the whole array and do something more complex than comparing to the value of another array. Why? Because the hash code is used for performance optimization only. So it should be way quicker than Equals. And Equals compares all the values.

When the arrays are different in size, Equals wouldnt't loop. Instead it returns immediately after comparing Length. Try to beat this in the hash code function.