How to write an equality method in Java

Consider adding the equality method to the following class of simple points:

public class Point {

    private final int x;
    private final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    // ...
}

// my definition is equal

public boolean equals(Point other) {
  return (this.getX() == other.getX() && this.getY() == other.getY());
}

What is wrong with this method? At first glance, it seems to work fine:

Point p1 = new Point(1, 2);
Point p2 = new Point(1, 2);

Point q = new Point(2, 3);

System.out.println(p1.equals(p2)); // prints true

System.out.println(p1.equals(q)); // prints false

However, the problem starts from the moment you start entering points in the collection:

import java.util.HashSet;

HashSet<Point> coll = new HashSet<Point>();
coll.add(p1);

System.out.println(coll.contains(p2)); // prints false

How can it be that coll does not contain p2, although p1 was added to it, and p1 and p2 were equal objects?

+5
source share
6 answers

Although it’s true that you must implement hashCode()when implementing equals(), that does not cause a problem.

This is not the method equals()you are looking for. The equals method should always have the following signature: "public boolean equals (Object object)". Here is the code.

public boolean equals(Object object)
{
  if (object == null)
  {
    return false;
  }

  if (this == object)
  {
    return true;
  }

  if (object instanceof Point)
  {
    Point point = (Point)object;
    ... now do the comparison.
  }
  else
  {
     return false;
  }
}

Apache EqualsBuilder . , .

Apache EqualsBuilder, , , Apache HashCodeBuilder.

: equals .

+8

hashCode() , equals(). , . , .

, . Java 2nd Edition, 9: hashCode .

+4

, hashcode!

: hashCode .

@Override public int hashCode() {
        return (41 * (41 + getX()) + getY());
    }

hashCode.

+2

equals() hashCode().

JavaDoc equals():

, hashCode , , hashCode, , -.

+1

:

Eclipse IDE, "Source" → "Generate hashCode() equals(), . , .

+1

equals hashCode ( , HashSet HashMap...). ( ) :

int hashCode() {
    return x * 31 + y;
}

( ): equals(Object), Object, . :

boolean equals(Object other) {
    if (other == this) return true;
    else if (!(other instanceof Point)) return false;
    else {
        Point p = (Point)other;
        return x == p.getX() && y == p.getY();
    }
}

, equals , , .

0

All Articles