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()
should be true
.
You can use some sort of commutative operation instead of what you have now, like addition:
I'd recommend that you still use the multiplier since it provides some entropy to your hash code. See my answer here, which says:
To solve you problem you have to combine both hashCodes of the components.
An example could be:
Please check if this matches your requirements. Also a multiplikation or an XOR insted of an addition could be possible.