How do I check for equality of values?
I am starting with Java, so please refrain from doing this.
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 am creating two instances:
Point a = new Point(1, 1);
Point b = new Point(1, 1);
I want to check if these two points are in the same place. The obvious way,, if (a == b) { ... }
does not work as it sounds like "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 this solution is not very good.
How can I take two Point Objects and check for equality, coordinate in a wise, elegant way?
source to share
The standard protocol is to implement the method equals()
:
class Point {
...
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Point)) return false;
Point rhs = (Point)obj;
return x == rhs.x && y == rhs.y;
}
Then you can use a.equals(b)
.
Note that once you've done this, you also need to implement the method hashCode()
.
For classes like yours, I use Apache Commons Lang a lot EqualsBuilder
and HashCodeBuilder
:
class Point {
...
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
source to share