1

単純なクラスがあるとします:

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

そして、1 番目と 2 番目のケースで、それぞれtrueとを取得します。false何が起こっている?このマップは値ではなくハッシュを比較していますか? 両方のケースで例が true を返すようにする方法は?

4

1 に答える 1

8

HashMap, notを使用しているため、クラスでand , notTreeMapをオーバーライドする必要があります。hashCodeequalscompareToPoint

@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;
}
于 2013-07-01T18:42:04.067 に答える