在
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的对象作为HashMap中的键和HashSet中的元素.
什么是hashCode函数的最佳候选者?我会把它翻一番,这样左边的部分是x,右边的部分是y,例如:
x = 4,y = 12,则hashCode返回4.12.但是通过实现,它不能是双重的,只能是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可能太长,所以一起它们不会被转换.