There is another use case: objects in which (some) fields should be compared without regard to their order . For example, if you want the pair (a, b) always be equal to the pair (b, a) .
XOR has the property that a ^ b = b ^ a , so it can be used in a hash function in such cases.
Examples: (full code here )
definition:
final class Connection { public final int A; public final int B; // some code omitted @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Connection that = (Connection) o; return (A == that.A && B == that.B || A == that.B && B == that.A); } @Override public int hashCode() { return A ^ B; } // some code omitted }
using:
HashSet<Connection> s = new HashSet<>(); s.add(new Connection(1, 3)); s.add(new Connection(2, 3)); s.add(new Connection(3, 2)); s.add(new Connection(1, 3)); s.add(new Connection(2, 1)); s.remove(new Connection(1, 2)); for (Connection x : s) { System.out.println(x); }
Sarge Borsch Mar 23 '14 at 13:25 2014-03-23 ββ13:25
source share