0

I have an array composed of an X number of 2DPoints, and my goal is to do a boolean operation that could check if that array has the specified 2DPoint. Something like this:

Point2D.Double arrayPoints[] = new Point2D.Double[numberOfPoints];
Point2D.Double pointPVariable = new Point2D.Double(positionXVariable,positionYVariable);
arrayPoints[variableNumber] = pointPVariable;

if(arrayPoints has the Point2D(2.45,6.52)){
    do this
}

How can I do that boolean operation?? Thank you very much!

jcasado94
  • 53
  • 1
  • 1
  • 3

2 Answers2

2
Arrays.asList(arrayPoints).contains(new Point2D.Double(2.45,6.52))

This works as long as the classes being compared override the equals method.

Darcara
  • 1,598
  • 1
  • 13
  • 33
  • I have discovered this array search method now, thank you. Until now, I was convinced the best method is to iterate the elements of the array and checking every element,but I think that doing this with one line of code is better :-). Is there any performance difference using this method than iterating and checking array with a for loop? – Alberto Solano Oct 09 '11 at 11:29
  • 1
    This does essentially the same thing. Both approaches are O(n). There is a small cost overhead, since the List has to be constructed, but that should be negligible, because it will be an ArrayList with only a reference (as opposed to a full copy) to the original array. – Darcara Oct 09 '11 at 11:38
1

If your array is sorted with the natural ordering of Point2D.Double, you can use the Arrays.binarySearch method.

if (Arrays.binarySearch(arraysPoints, new Point2D.Double(2.45,6.52)) >= 0) {
    do this
}
YMomb
  • 2,366
  • 1
  • 27
  • 36