在 HashSet 中存储坐标

Storing coordinates in HashSet

我正在尝试将坐标存储在 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

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

我也看过其他问题,不建议在集合中使用数组。

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

为存储坐标数据创建class

class Coordinate{
   Integer x;
   Integer y;
}

并为 class 实现等号和哈希码。

或者您可以使用 List<Integer> 代替 int[]

HashSet<List<Integer>> hSet = new HashSet<>();
hSet.add(List.of(1, 2));
hSet.add(List.of(3, 4));
System.out.println(hSet.contains(List.of(1, 2)));

List接口的equals()方法比较指定对象与该集合是否相等。如果两个列表具有相同的元素并且大小相同,它 returns 一个布尔值 true。

您可以(最好...应该)创建一个自己的 class 来保存这些坐标:

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

现在最重要的是实现equals and 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;
    }
}

准备好后,您可以将代码更改为:

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

这会打印出来

true

随心所欲。