在 Java 中,我有一个类,它表示具有 int 坐标的点
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;
}
}
我使用类的对象Point作为 a 中的键和 aHashMap中的元素HashSet。
该功能的最佳候选者是hashCode什么?我会把它加倍,这样左边的部分是 x,右边的部分是 y,例如:
x = 4, y = 12,然后hashCode返回4.12。但是通过实现,它不能是double,只能是int。
这不是一个选项:
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));
}
因为值x和y可以太长,这样它们就不会一起被转换。