如何使我的HashMap按预期工作?

时间:2013-07-01 18:40:44

标签: java hashmap

假设有一个简单的类:

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;
    }
}

HashMapPoint到某事,我们说CellcellMap = 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));
}

分别获得truefalse第一和第二种情况。到底是怎么回事?这张地图比较哈希值而不是值吗?如何使示例在两种情况下都返回true?

1 个答案:

答案 0 :(得分:8)

由于您使用的是HashMap,而不是TreeMap,因此您需要在hashCode中覆盖equalscompareTo,而不是Point类:

@Override
public int hashCode() {
    return 31*x + y;
}
@Override
public bool equals(Object other) {
    if (other == null) return false;
    if (other == this) return true;
    if (!(other instanceof Point)) return false;
    Point p = (Point)other;
    return x == p.x && y == p.y;
}