How to make two objects equal in contains method of Hashset

Viewed 63

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
  }
}
2 Answers

It is generally necessary to override the hashCode method whenever equals method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

import java.util.HashSet;

class Point extends Object {
    int x, y, dis;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
        this.dis = (int) Math.sqrt(x * x + y * y);
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Point) {
            Point p = (Point) o;
            return p.x == x && p.y == y;
        }
        return false;
    }

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

public class Equals {
    public static void main(String[] args) {
        HashSet<Point> set = new HashSet<Point>();
        set.add(new Point(1, 2));
        set.add(new Point(1, 2));
        set.add(new Point(1, 3));
        System.out.println(set.size());
    }
}

See equals API doc.

Related