ArrayList of my objects, indexOf problem

后端 未结 4 1480
一个人的身影
一个人的身影 2021-01-20 12:04

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

4条回答
  •  情歌与酒
    2021-01-20 12:27

    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).

    See also

    • Java Language Guide: the for-each loop
    • java.util.List API

    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 implementsComparable, using x 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, not a List.

    See also

    • 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?

提交回复
热议问题