问题描述
我需要Java中的hashCode
实现,该实现忽略类Edge
中字段的顺序.
I need a hashCode
implementation in Java which ignores the order of the fields in my class Edge
. It should be possible that Node first could be Node second, and second could be Node first.
这是我的方法取决于顺序:
Here is my method is depend on the order:
public class Edge {
private Node first, second;
@Override
public int hashCode() {
int hash = 17;
int hashMultiplikator = 79;
hash = hashMultiplikator * hash
+ first.hashCode();
hash = hashMultiplikator * hash
+ second.hashCode();
return hash;
}
}
是否有一种方法可以计算出以下边缘相同但唯一的哈希值?
Is there a way to compute a hash which is for the following Edges the same but unique?
Node n1 = new Node("a");
Node n2 = new Node("b");
Edge ab = new Edge(n1,n2);
Edge ba = new Edge(n2,n1);
ab.hashCode() == ba.hashCode()
应该是true
.
推荐答案
您可以使用某种交换运算来代替现在的运算,例如加法运算:
You can use some sort of commutative operation instead of what you have now, like addition:
@Override
public int hashCode() {
int hash = 17;
int hashMultiplikator = 79;
int hashSum = first.hashCode() + second.hashCode();
hash = hashMultiplikator * hash * hashSum;
return hash;
}
我建议您仍然使用乘数,因为它为您的哈希码提供了一些熵.请参见在这里我的答案,其中说:
I'd recommend that you still use the multiplier since it provides some entropy to your hash code. See my answer here, which says:
- 混合您的运营商.通过混合您的运算符,您可以导致结果变化更大.在此测试中仅使用
x * y
,我有一个非常 大量的碰撞. - 使用质数进行乘法运算.质数具有有趣的二进制性质,导致乘法更不稳定.
- 避免使用移位运算符(除非您真的知道自己在做什么).他们将许多零或一插入到 数量,减少其他业务的波动性,甚至可能 减少可能的输出数量.
- Mix up your operators. By mixing your operators, you can cause the results to vary more. Using simply
x * y
in this test, I had a very large number of collisions. - Use prime numbers for multiplication. Prime numbers have interesting binary properties that cause multiplication to be more volatile.
- Avoid using shift operators (unless you really know what you're doing). They insert lots of zeroes or ones into the binary of the number, decreasing volatility of other operations and potentially even shrinking your possible number of outputs.
这篇关于具有两个无序字段的唯一hashCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!