Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

java - 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 ( (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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...