Search code examples
javacontainshashset

How to make two objects equal in contains method of Hashset


I have created a Pair Class which has 3 variables mentioned below and overrides the equals method as well assuming this is used in contains method of hashset. But it is not. Can someone explain what to implement in Pair class to make sure it equats the values of x and y only.

Class Pair extends Object {
int x;
int y;
int dis;
   public Pair(int x, int y, int d) {
    this.x = x;
    this.y = y;
    this.dis = d;
   }
  @override
  public boolean equals(Pair p) {
  return this.x == p.x && this.y == p.y
  }
}

Solution

  • Whenever you overide equals, you should also override hashCode:

    @Override
    public int hashCode() {
        return Objects.hash(x,y);
    }
    

    See the general contract of equals and hashCode: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html