简体   繁体   中英

Best way to define a hashcode method for char array

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;
}

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.

如果您有一个包含字符数组的对象并且您想覆盖 hashCode() 那么您可以使用它的方法:

java.util.Arrays.hashCode()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM