首页 > 解决方案 > 如何逐点获取地图中的值?

问题描述

我有一point堂课:

class Point
{
    public int x;
    public int y;

    public Point(int x,int y) 
    {
        this.x=x;
        this.y=y;
    }
}

我有一个map存储值:

Map<Point,Integer> map = new HashMap<Point,Integer>();
map.put(new point(1,1)) = 10;

我想map通过一个明确的点来获取值:

map.get(new point(1,1));

但它返回null。这可能是因为他们的参考不同。我想知道如何修复它,而不是使用二维数组。

标签: java

解决方案


当使用 Map 类之类的结构时,您应该实现 equals 和 hashCode 方法,因此当 Map 的 get 方法被调用时,这些方法将分别调用

像这样的东西:

class Point {
    public int x;
    public int y;

    public Point(int x,int y)
    {
        this.x=x;
        this.y=y;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        Point point = (Point) o;
        return x == point.x && y == point.y;
    }

    @Override
    public int hashCode() {
        return Objects.hash(x, y);
    }
}

推荐阅读