In Java, I have a class that represents a point with int coordinates
public class Point {
int x = -1;
int y = -1;
public Point (int xNew, int yNew) {
x = xNew; y = yNew;
}
public boolean equals (Object o) {
// no need for (o instanceof Point) by design
return x == ((Point)o).x && y == ((Point)o).y;
}
}
I'm using objects of class Point
as keys in a HashMap
and as elements in a HashSet
.
What would be the best candidate for the hashCode
function? I would make it double so that the left part is x and the right part is y, for example:
x = 4, y = 12
, then the hashCode
returns 4.12
. But by the implementation, it cannot be double, only int.
This is not an option:
public int hashCode() {
// no need to check for exception parseInt since x and y are valid by design
return Integer.parseInt(Integer.toString(x) + Integer.toString(y));
}
because values x
and y
can be too long, so that together they will not be converted.