Shailen
Shailen

Reputation: 8347

How to search an array of coordinates in Java?

I have an array in Java. Each entry of array is a pair of numbers (x and y coordinates).

Technically, an example of my array is:

setOfPoints = {(1,2), (3,4), (5,6), (1,9), (7,4)}

How can I search that list and check whether (3,4) is part of that set?

Ideally, I would like to do a Java function isCoordinateInSet((3,4), setOfPoints). I would also like to avoid using for loops that could potentially increase the time of operation. I am thinking of using Java Maps fpr this task. What do you think?

I am not following the Java syntax above, but I described it as so, to better explain what I want to do.

I would appreciate your input.

Thank you.

Upvotes: 1

Views: 3847

Answers (3)

Liviu Stirb
Liviu Stirb

Reputation: 6075

public class Point{

    private int x,y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Point point = (Point) o;

        if (x != point.x) return false;
        if (y != point.y) return false;

        return true;
    }

    @Override 
    public int hashCode() {
        int result = x;
        result = 31 * result + y;
        return result;
    }
}

    Set<Point> points = new HashSet<>();
    points.add(new Point(3,4));
    points.add(new Point(5,6));
    points.add(new Point(1,2));
    points.add(new Point(3,5));

    System.out.println(points.contains(new Point(3,4)));
    System.out.println(points.contains(new Point(1,2)));
    System.out.println(points.contains(new Point(2,4)));

Upvotes: 3

Juvanis
Juvanis

Reputation: 25950

Apache commons library has a class named MultiHashMap which is in org.apache.commons.collections package. I think you can use MultiHashMap for searching a particular coordinate.

MultiMap mhm = new MultiHashMap();
mhm.put(3,5);
mhm.put(3,4);
mhm.put(5,6);
mhm.put(3,8);
List list = (List) mhm.get(3);

list will contain 5,4 and 8. After you find x-coordinate value, you will search for y-coordinate in this list.

Upvotes: 0

assylias
assylias

Reputation: 328629

You could create a class Coordinate that holds the (x,y) pair and override its equals/hashcode methods to make two instances having the same x and y be equal.

Then you create one Coordinate instance per pair in your array and add them to a Set<Coordinate>, for example a HashSet.

Then you isCoordinateInSet is simply a call to set.contains(new Coordinate(3,4));.

Upvotes: 3

Related Questions