Java 在HashSet中存储坐标

Java 在HashSet中存储坐标,java,coordinates,hashset,Java,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 HashSet hSet=newhashset

我试图将坐标存储在哈希集中,并检查我的哈希集中是否存在坐标

    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
HashSet hSet=newhashset();
hSet.add(新的int[]{1,2});
hSet.add(新的int[]{3,4});
System.out.println(hSet.contains(newint[]{1,2}));
>>>假的
我对Java相当陌生,据我所知,上面的输出为false是因为比较int[]数组的引用,而不是它们值的逻辑比较。但是,使用Arrays.equals()将不会使用hashset的哈希,因为我必须迭代它的所有元素

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


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

为存储坐标数据创建一个类

class Coordinate{
   Integer x;
   Integer y;
}
并为类实现equals和hashcode

或者,您可以通过这种方式使用
List
而不是
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)));
HashSet hSet=newhashset();
hSet.add(第(1,2)项列表);
hSet.add(第(3,4)项列表);
System.out.println(hSet.contains(列表1,2));
List接口的equals()方法将指定对象与此集合进行相等性比较。如果两个列表具有相同的元素且大小相同,则返回布尔值true。

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

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; }
}
现在,最重要的是实施:

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

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)));
}
publicstaticvoidmain(字符串[]args){
HashSet hSet=新的HashSet();
hSet.add(新坐标(1,2));
hSet.add(新坐标(3,4));
System.out.println(hSet.contains(新坐标(1,2));
}
这是打印出来的

真的


根据需要。

创建您自己的
坐标
类,并实现
等于
哈希码
?因此没有用于此目的的内置类?可能是
java.awt.Point
。这取决于您打算在其中使用该类的上下文。
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)));
}