Consider adding the equality method to the following class of simple points:
public class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
// my definition is equal
public boolean equals(Point other) {
return (this.getX() == other.getX() && this.getY() == other.getY());
}
What is wrong with this method? At first glance, it seems to work fine:
Point p1 = new Point(1, 2);
Point p2 = new Point(1, 2);
Point q = new Point(2, 3);
System.out.println(p1.equals(p2));
System.out.println(p1.equals(q));
However, the problem starts from the moment you start entering points in the collection:
import java.util.HashSet;
HashSet<Point> coll = new HashSet<Point>();
coll.add(p1);
System.out.println(coll.contains(p2));
How can it be that coll does not contain p2, although p1 was added to it, and p1 and p2 were equal objects?
source
share