How to check for value equality?

2020-02-06 12:57发布

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?

标签: java
2条回答
家丑人穷心不美
2楼-- · 2020-02-06 13:34

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);
  }
}
查看更多
对你真心纯属浪费
3楼-- · 2020-02-06 13:53

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)) { ... }
查看更多
登录 后发表回答