Java – ArrayList and indexof problems of my objects
I have an ArrayList problem with Java I created an object that contains two attributes X and Y. now I loaded some objects in ArrayList The problem is that I don't know how to use the X attribute I'm searching to find the index of an object Is there any way to do this?
Solution
Suppose there is something similar:
public class Point { public final int x; public final int y; }
And declare that:
List<Point> points = ...;
You can use for each to iterate over all points and find the points you want:
for (Point p : points) { if (p.x == targetX) { process(p); break; // optional } }
Note that this does not provide you with an index, but it provides you with the point itself, which is sometimes sufficient If you really need an index, you want to use the indexed for loop, using size () and get (int index) (see balusc's answer)
You can also have a look
> Java Language Guide: the for-each loop > java. util. List API
The above solution searches o (n) for each targetx If you do this often, you can improve this by declaring the class point implementationcomparable < point >, using X as collections The main sort key for sort
Then you can collect binarySearch. Set the time to o (n log n), and you can now answer each query in O (log n)
Another option is to use sortedset, such as TreeSet, especially if you have set < point > instead of list < point >
You can also have a look
> How to sort an array or ArrayList