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
- Dcheck_circle
true
Explanation
Equal objects must have equal hashCodes. Both points have x=1, y=2, so equals is true and hashCodes are equal.