Overriding Methods

AP Computer Science A· difficulty 4/5

public class Point {
    private int x, y;
    public Point(int a, int b) { x = a; y = b; }
    public boolean equals(Object o) {
        if (!(o instanceof Point)) return false;
        Point p = (Point) o;
        return x == p.x && y == p.y;
    }
    public int hashCode() { return x * 31 + y; }
}
// Usage:
Point a = new Point(1, 2);
Point b = new Point(1, 2);
System.out.print(a.equals(b) && a.hashCode() == b.hashCode());

What is printed?

  • A

    0

  • B

    Compile error

  • C

    false

  • D

    true

    check_circle

Explanation

Equal objects must have equal hashCodes. Both points have x=1, y=2, so equals is true and hashCodes are equal.

Want 10 more like this — adaptive to your weak spots?

Related questions