gpt4 book ai didi

java - 在 HashSet 中存储坐标

转载 作者:行者123 更新时间:2023-12-02 02:47:57 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com