How to check for value equality?

前端 未结 2 1846
遥遥无期
遥遥无期 2020-12-11 10:03

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


        
相关标签:
2条回答
  • 2020-12-11 10:13

    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);
      }
    }
    
    0 讨论(0)
  • 2020-12-11 10:29

    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)) { ... }
    
    0 讨论(0)
提交回复
热议问题