我需要一个hashCodeJava实现,它忽略了我的类中字段的顺序Edge.Node首先可能是Node第二个,第二个可能是Node第一个.
这是我的方法取决于顺序:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法计算一个哈希值,这个哈希值对于以下边缘是相同但唯一的?
Node n1 = new Node("a");
Node n2 = new Node("b");
Edge ab = new Edge(n1,n2);
Edge ba = new Edge(n2,n1);
Run Code Online (Sandbox Code Playgroud)
ab.hashCode() == ba.hashCode()应该是true.
您可以使用某种可交换操作而不是现在的操作,例如:
@Override
public int hashCode() {
int hash = 17;
int hashMultiplikator = 79;
int hashSum = first.hashCode() + second.hashCode();
hash = hashMultiplikator * hash * hashSum;
return hash;
}
Run Code Online (Sandbox Code Playgroud)
I'd recommend that you still use the multiplier since it provides some entropy to your hash code. See my answer here, which says:
Some good rules to follow for hashing are:
- Mix up your operators. By mixing your operators, you can cause the results to vary more. Using simply
x * yin 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.