2

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
  }
}
Al Pa chino
  • 75
  • 2
  • 8

2 Answers2

0

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

Hanchen Jiang
  • 2,514
  • 2
  • 9
  • 20
0

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.

p2kr
  • 606
  • 6
  • 18