2

I am trying to store coordinates in a HashSet and checking whether a coordinate exist inside my set.

    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

I am rather new to Java and from my understanding the output of the above is false is due to comparing the references of the int[] arrays rather than the logical comparison of their values. However using Arrays.equals() would not be making use of the hashing of the hashset as I would have to iterate over all its elements.

I have also read on other questions that it is not recommended to use arrays inside collections.

So if I wish to store coordinate pairs inside a HashSet, what data structure should I use so that I can search for an element using the hashcode?

Ayam Chan
  • 75
  • 7

2 Answers2

5

You could (better ... should) create an own class that holds those coordinates:

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

Now, the most important thing is to implement 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;
    }
}

With that preparation, you can change your code to:

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

This prints out

true

as wanted.

Community
  • 1
  • 1
Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66
0

Create a class for store Coordinate data

class Coordinate{
   Integer x;
   Integer y;
}

And implement equals and hashcode for the class.

Or you can use List<Integer> instead of int[] this way.

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

The equals() method of List interface compares the specified object with this collection for equality. It returns a Boolean value true if both the lists have same elements and are of the same size.

Eklavya
  • 17,618
  • 4
  • 28
  • 57