简体   繁体   中英

How to check for value equality?

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 ( (ax == bx) && (ay == by) ) { ... } , 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:

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)) { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM