Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing hashcode for an object with "interchangeable" fields [duplicate]

Tags:

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?

like image 920
James Avatar asked Feb 07 '20 12:02

James


1 Answers

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.

like image 122
Karol Dowbecki Avatar answered Sep 18 '22 11:09

Karol Dowbecki