简体   繁体   English

为字符数组定义哈希码方法的最佳方法

[英]Best way to define a hashcode method for char array

Best way to define a hashcode method for char array.为 char 数组定义哈希码方法的最佳方法。 Is there a better way to implement our own hascode() method for minimum collision?有没有更好的方法来实现我们自己的 hascode() 方法来最小化冲突?

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 .所以它应该比Equals快得多。 And Equals compares all the values.并且Equals比较所有值。

When the arrays are different in size, Equals wouldnt't loop.当数组大小不同时, Equals不会循环。 Instead it returns immediately after comparing Length .相反,它在比较Length后立即返回。 Try to beat this in the hash code function.尝试在哈希码函数中击败它。

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

java.util.Arrays.hashCode()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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