I'm a Java-beginner, so please bear with this one.
I have a class:
class Point {
public int x;
public int y;
public Point (int x, int y) {
this.x = x;
this.y = y;
}
}
I create two instances:
Point a = new Point(1, 1);
Point b = new Point(1, 1);
I want to check if these two points are at the same place. The obvious way, if (a == b) { ... }
, does not work since this seems to be an "are the objects equal?" kind of test, which is not what I want.
I can do if ( (a.x == b.x) && (a.y == b.y) ) { ... }
, but that solution does not feel good.
How can I take two Point-objects and test them for equality, coordinate wise, in an elegant way?
The standard protocol is to implement the
equals()
method:Then you can use
a.equals(b)
.Note that once you've done this, you also need to implement the
hashCode()
method.For classes like yours, I often use Apache Commons Lang's
EqualsBuilder
andHashCodeBuilder
:You'll want to override the
hashCode()
andequals()
method. If you're using Eclipse, you can have Eclipse do this for you by going toSource -> Generate hashCode() and equals()..
. After you override these methods, you can call: