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 ASC first by x and then by y? > Java: What is the difference between implementing Comparable and Comparator?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>