I'm trying to make class Point
work correctly with a HashSet. Here is my Point class:
class Point {
int x;
int y;
Point(int x, int y) {
x = x;
y = y;
}
@Override
public int hashCode() {
int hash = 1;
hash = hash * 17 + x;
hash = hash * 31 + y;
return hash;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
Point p = (Point) o;
return x == p.x && y == p.y;
}
}
When I test it out and do
HashSet<Point> h = new HashSet<Point>();
h.add(new Point(0, 0));
Point g = new Point(0, 1);
System.out.println(h.equals(g));
System.out.println(h.contains(g));
The output is this
false
true
Why is my hashCode not working?