Since none of the answers mention this approach, I would like to add this approach:
public class UnorderedPair<T> { final T first, second; public UnorderedPair(T first, T second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (!(o instanceof UnorderedPair)) return false; UnorderedPair<T> up = (UnorderedPair<T>) o; return (up.first == this.first && up.second == this.second) || (up.first == this.second && up.second == this.first); } @Override public int hashCode() { int hashFirst = first.hashCode(); int hashSecond = second.hashCode(); int maxHash = Math.max(hashFirst, hashSecond); int minHash = Math.min(hashFirst, hashSecond);
Note that you should adhere to the common hashCode() and equals() contract:
- If you override
hashCode() or equals() you should also override another method. - If
equals returns true for 2 objects, then the hashCode() method should return the same int value for both objects. - If
hashCode() returns the same int for 2 objects, then it is not necessarily true that the equals() method returns true .
The above implementation of the equals() and hashCode() method provides this.
source share