Unique hash code with two fields without order

I need a hashCode implementation in Java that ignores the order of fields in my Edge class. It should be possible that Node may first be Node second, and Node may be second.

Here is my method depends 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 calculate a hash that is the same but unique for the following Edges?

 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() must be true .

+4
source share
2 answers

You can use some kind of commutative operation instead of what you have now, for example, an addition:

 @Override public int hashCode() { int hash = 17; int hashMultiplikator = 79; int hashSum = first.hashCode() + second.hashCode(); hash = hashMultiplikator * hash * hashSum; return hash; } 

I would recommend you use a multiplier, as it provides some entropy to your hash code. See my answer here , which says:

Some good rules for hashing:

  • Mix your operators. By mixing your operators, you can make the results change more. Using just 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 lead to more unstable multiplication.
  • Avoid using shift operators (unless you really know what you are doing). They insert many zeros or ones into a binary code number, reducing the volatility of other operations and potentially even reducing your possible number of outputs.
+4
source

To solve your problem, you need to combine both component hash codes.

An example would be:

 @Override public int hashCode() { int prime = 17; return prime * (first.hashCode() + second.hashCode()); } 

Please check if this meets your requirements. Animation or XOR increment of addition is also possible.

+2
source

Source: https://habr.com/ru/post/1485366/


All Articles