Giiovanna
Giiovanna

Reputation: 442

Closest point of a set to a given point

I have a ArrayList of 2 dimensional points represented by this class. I get the x and y coordinates from a mouse click of the user and I have to find the closest point at this set to the point obtained by the user's mouse. I've find the following topic while I was trying to solve this

find closest point from users coordinates

The Point2D class have a comparator called DISTANCE_TO_ORDER that compares two points using the distance to a third one. I've tried the following to obtain the closest point:

public Point2D closestPoint(Point2D p){
    return Collections.min(points, p.DISTANCE_TO_ORDER);
}

but I get the error: Exception in thread "main" java.util.NoSuchElementException when I try

Point2D p = new Point2D(-46.73081652, -23.557997478347108);
Point2D c = gps.closestPoint(p);

What am I doing wrong? I've tried to implement something like the topic, but didn't work. Can someone help me to solve this?

PS: I have to use the Point2D class.

Thanks!

Upvotes: 0

Views: 691

Answers (1)

Thomas
Thomas

Reputation: 88757

From the JavaDoc on Collections.min(collection, comparator):

throws NoSuchElementException if the collection is empty.

Hence most probably points is empty.

Upvotes: 4

Related Questions