java - 在 HashSet 中存储坐标

标签 java coordinates 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 相当陌生,根据我的理解,上面的输出是 false 是由于比较 int[] 数组的引用而不是它们的值的逻辑比较。但是,使用 Arrays.equals() 不会利用哈希集的哈希,因为我必须迭代其所有元素。

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

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

最佳答案

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

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

如所愿。

关于java - 在 HashSet 中存储坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62483329/

相关文章:

java - Android - 在 map 中仅显示确定区域中包含的标记

Python win32com和二维数组

java - 从交集java获取第一个元素

java - 如何从文档文本中过滤常用词? ( HashMap )

java - 如何在 Liferay 中隐藏 portlet 图标和标题但保留编辑控件?

java - 按锁定按钮时声音停止

java - testng.xml 未运行类

python-3.x - python中的随机函数在圆内生成随机对

java - 如何在 BorderLayout 的中心使用 JScrollpane

java - 计算大长数组中的不同值(性能问题)