I have problem with Java\'s ArrayList. I\'ve created an Object, that contains two attributes, x and y. Now I\'ve loaded some object in my ArrayList. Problem is that I don\'t
Assuming something like:
public class Point {
public final int x;
public final int y;
}
And a declaration of:
List points = ...;
You can use for-each to iterate through all the points and find the one you want:
for (Point p : points) {
if (p.x == targetX) {
process(p);
break; // optional
}
}
Note that this will not give you the index, but it will give you the Point
itself, which sometimes is enough. If you really need the index, then you'd want to use indexed for loop, using size()
and get(int index)
(see BalusC's answer).
The above solution searches in O(N)
for each targetX
. If you're doing this often, then you can improve this by declaring class Point implements
Comparablex
as the primary sorting key for Collections.sort.
Then you can Collections.binarySearch. With a setup time of O(N log N)
, each query can now be answered in O(log N)
.
Another option is to use a SortedSet such as a TreeSet, especially if what you have is a Set