在 HashSet 中存储坐标

Aya*_*han 2 java hashset coordinates

我正在尝试将坐标存储在 HashSet 中并检查我的集合中是否存在坐标。

    HashSet<int[]> hSet = new HashSet<>();
    hSet.add(new int[] {1, 2});
    hSet.add(new int[] {3, 4});
    System.out.println(hSet.contains(new int[] {1, 2}));

>>> false
Run Code Online (Sandbox Code Playgroud)

我对 Java 比较陌生,根据我的理解,上面的输出为 false 是由于比较了 int[] 数组的引用,而不是它们值的逻辑比较。但是,使用 Arrays.equals() 不会使用散列集的散列,因为我必须遍历其所有元素。

我还阅读了其他问题,不建议在集合中使用数组。

因此,如果我希望在 HashSet 中存储坐标对,我应该使用什么数据结构,以便我可以使用哈希码搜索元素?

See*_*ose 5

您可以(更好……应该)创建一个自己的类来保存这些坐标:

public class Coordinates {
    private final int x;
    private final int y;

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

    public int getX() { return x; }
    public int getY() { return y; }
}
Run Code Online (Sandbox Code Playgroud)

现在,最重要的是实现equals和hashCode:

public class Coordinates {
    ...

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Coordinates other = (Coordinates) obj;
        return this.x == other.x && this.y == other.y;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + x;
        result = prime * result + y;
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

通过这些准备,您可以将代码更改为:

public static void main(String[] args) {
    HashSet<Coordinates> hSet = new HashSet<>();
    hSet.add(new Coordinates(1, 2));
    hSet.add(new Coordinates(3, 4));
    System.out.println(hSet.contains(new Coordinates(1, 2)));
}
Run Code Online (Sandbox Code Playgroud)

这打印出来

真的

随心所欲。