假设有一个简单的类:
public class Point implements Comparable<Point> {
public int compareTo(Point p) {
if ((p.x == this.x) && (p.y == this.y)) {
return 0;
} else if (((p.x == this.x) && (p.y > this.y)) || p.x > this.x) {
return 1;
} else {
return -1;
}
}
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
还有一个HashMap
从Point
到某事,让我们说Cell
:
cellMap = new HashMap<Point, Cell>();
然后填写cellMap
如下:
for (int x = -width; x <= width; x++) {
for (int y = -height; y <= height; y++) {
final Point pt = new Point(x,y);
cellMap.put(pt, new Cell());
}
}
}
然后做类似(微不足道的)这样的事情:
for (Point pt : cellMap.keySet()) {
System.out.println(cellMap.containsKey(pt));
Point p = new Point(pt.getX(), pt.getY());
System.out.println(cellMap.containsKey(p));
}
并分别在第一种和第二种情况下得到true
和。false
到底是怎么回事?这张地图是在比较哈希而不是值吗?如何使示例在这两种情况下都返回 true?