Java equals, hashCode, and toString

By default, two objects are equal only if they are the same object. A class that represents a value, such as a point, should override equals so that two points with the same coordinates count as equal. It must then also override hashCode so that equal objects have the same hash code, otherwise hash-based collections such as HashSet and HashMap behave incorrectly.

Java
import java.util.*;

class Main {
  static class Point {
    private final int x;
    private final int y;

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

    @Override
    public boolean equals(Object other) {
      if (this == other) {
        return true;
      }
      if (!(other instanceof Point)) {
        return false;
      }
      Point p = (Point) other;
      return x == p.x && y == p.y;
    }

    @Override
    public int hashCode() {
      return Objects.hash(x, y);
    }

    @Override
    public String toString() {
      return "(" + x + "," + y + ")";
    }
  }

  public static void main(String[] args) {
    Point a = new Point(1, 2);
    Point b = new Point(1, 2);
    System.out.println((a == b) + " " + a.equals(b));

    Set<Point> seen = new HashSet<>();
    seen.add(a);
    seen.add(b);
    seen.add(new Point(3, 4));
    System.out.println(seen.size() + " " + seen.contains(new Point(3, 4)));
    System.out.println(a + " " + (a.hashCode() == b.hashCode()));
  }
}
Read the full lesson