Consider adding an 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 of equals
public boolean equals(Point other) {
return (this.getX() == other.getX() && this.getY() == other.getY());
}
What’s wrong with this method? At first glance, it seems to work OK:
Point p1 = new Point(1, 2);
Point p2 = new Point(1, 2);
Point q = new Point(2, 3);
System.out.println(p1.equals(p2)); // prints true
System.out.println(p1.equals(q)); // prints false
However, trouble starts once you start putting points into a collection:
import java.util.HashSet;
HashSet<Point> coll = new HashSet<Point>();
coll.add(p1);
System.out.println(coll.contains(p2)); // prints false
How can it be that coll does not contain p2, even though p1 was added to it, and p1 and p2 are equal objects?
While it is true that you should implement
hashCode()when you implementequals(), that is not causing your problem.That is not the
equals()method you are looking for. The equals method must always have the following signature: “public boolean equals(Object object)”. Here is some code.The Apache EqualsBuilder class is useful for equals implementations. The link is an older version, but still applicable.
If you liked the Apache EqualsBuilder, you will probably like the Apache HashCodeBuilder class as well.
Edit: updated the equals method example for standard shortcuts.