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) {
The standard protocol is to implement the equals() method:
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 hashCode() method.
For classes like yours, I often use Apache Commons Lang's EqualsBuilder and HashCodeBuilder:
class Point {
...
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
You'll want to override the hashCode()
and equals()
method. If you're using Eclipse, you can have Eclipse do this for you by going to Source -> Generate hashCode() and equals()..
. After you override these methods, you can call:
if(a.equals(b)) { ... }