Equals HashCode Contract Hand Written
Write equals and hashCode by hand on a plain class so equal objects land in the same HashSet bucket and contains finds them.
Code
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class PointKey {
static final class Point {
final int x;
final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
// 相等的对象必须有相同 hashCode,否则 HashSet 找不回来
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof Point p)) return false;
return x == p.x && y == p.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
public static void main(String[] args) {
Set<Point> visited = new HashSet<>();
visited.add(new Point(1, 2));
System.out.println("contains equal point: " + visited.contains(new Point(1, 2)));
System.out.println("re-add rejected: " + !visited.add(new Point(1, 2)));
}
}How the snippet works
Equals HashCode Contract Hand Written comes down to the classes PointKey and Point and the functions equals, hashCode and main.
Applying it
The main signature reads public boolean equals(Object other)
The demo output is labeled (contains equal point:, re-add rejected:), so every printed line maps back to its originating operation.
Statements that matter
if (!(other instanceof Point p)) return false;
if (this == other) return true;
return x == p.x && y == p.y;
Interactive Tools for This Topic
FAQ
- What does Equals HashCode Contract Hand Written print when run?
- Invoke the file as-is — the `contains equal point:`, `re-add rejected:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.