I want two instances of the Pair class to be treated as equal if "first" and "second" are swapped, i.e. Pair(1,2) == Pair(2,1) should evaluate true.
static class Pair {
int first;
int second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
Pair that = (Pair) obj;
return (this.first == that.first && this.second == that.second)
|| (this.second == that.first && this.first == that.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second) + Objects.hash(second, first);
}
}
I have come up with this hashcode(), and it seems to work, but is there an better / generally accepted way of doing this?
A simpler hash code without overhead of Objects.hash()
would be:
@Override
public int hashCode() {
return first + second;
}
It's similar to what Integer.hashCode()
which returns the Integer
value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With