-2

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;
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
shubham26
  • 11
  • 3
  • why you want to do this? I suppose that you have an object that contains an array of chars, right? – vmrvictor Oct 04 '18 at 10:51
  • 4
    Have you already tried `Arrays.hashCode(char a[])` ? – LuCio Oct 04 '18 at 10:51
  • When asking for help, take the time to ensure your question is complete, clear, and formatted correctly. Code is not a quote, don't use blockquote for it. **Do** put linebreaks in reasonable places, format and indent the code in a consistent, readable way, etc. – T.J. Crowder Oct 04 '18 at 10:52
  • @LuCio : I was trying not to use the API method. – shubham26 Oct 04 '18 at 10:56
  • 3
    Why? What's wrong with it? Do you have some requirements which are not matched by `Arrays.hashCode()`? Or is it just an exercise? – LuCio Oct 04 '18 at 10:58
  • Unless you define your criteria for "best" precisely, any attempts to suggest a "better" hash code algorithm are either opinion or guess work. Even saying you want minimum collision is imprecise unless you give a clear domain over which you want to minimize the collisions. – Stephen C Oct 04 '18 at 11:04

2 Answers2

1

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.

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
-1

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()
vmrvictor
  • 683
  • 7
  • 25