The Object Class: equals and hashCode

The parent of everything

If a class doesn't say extends, Java makes it extend Object. So every class has Object's methods, including toString(), equals() and hashCode().

equals for your own classes

By default, equals works like ==: it is only true for the very same object. Two separate objects with the same data are not equal:

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

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

Output

false

Override equals to compare the data instead. Whenever you override equals, also override hashCode so that equal objects give the same number (HashMap and HashSet rely on this):

import java.util.Objects;

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

    @Override
    public boolean equals(Object other) {
        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);
    }
}

public class Main {
    public static void main(String[] args) {
        Point a = new Point(1, 2);
        Point b = new Point(1, 2);
        Point c = new Point(5, 5);
        System.out.println(a.equals(b));
        System.out.println(a.equals(c));
        System.out.println(a.hashCode() == b.hashCode());
    }
}

Output

true
false
true

Remember: Override equals and hashCode together – never one without the other.

HOME LABS COMMUNITY DASHBOARD