ArrayList of my objects, indexOf problem

I have a problem with Java ArrayList. I created an object containing two attributes: x and y. Now I have loaded some object into my ArrayList. The problem is that I don’t know how to find the index of any object with the x attribute that I am looking for. Is there any way to do this?

+3
source share
4 answers

Assuming something like:

public class Point {
   public final int x;
   public final int y;
}

And the announcement:

List<Point> points = ...;

You can use for-each to repeat all points and find what you want:

for (Point p : points) {
   if (p.x == targetX) {
      process(p);
      break; // optional
   }
}

, , Point, . , , size() get(int index) (. BalusC).

.


O(N) targetX. , , class Point implements Comparable<Point>, x Collections.sort.

Collections.binarySearch. O(N log N) O(log N).

- SortedSet, TreeSet, Set<Point>, List<Point>.

.

+7

, ?

public class Point {

private final int x;
private final int y;

public Point(int x, int y) {
    this.x = x;
    this.y = y;
}

public int getX() {
    return x;
}

public int getY() {
    return y;
}

@Override
public boolean equals(Object o) {
    return (o instanceof Point && getX() == ((Point) o).getX() && getY() == ((Point) o)
            .getY());

}

}

public class TestIndexOf {

public static void main(String[] args){
    Point p1 = new Point(10,30);
    Point p2 = new Point(20,40);
    Point p3 = new Point(50,40);
    Point p4 = new Point(60,40);
    List<Point> list = new ArrayList<Point>();
    list.add(p1);
    list.add(p2);
    list.add(p3);
    list.add(p4);
    System.out.println(list.indexOf(p3));
}

}

x, equals, x, :

@Override
public boolean equals(Object o) {
    return (o instanceof Point && getX() == ((Point) o).getX());

}
+7

.

for (int i = 0; i < list.size(); i++) {
    if (list.get(i).getX() == someValue) { // Or use equals() if it actually returns an Object.
        // Found at index i. Break or return if necessary.
    }
}

, , , , JDK7 Closures, .

+5

, , . , , .

Map<String, Object> map = new HashMap<String, Object>();

map.put(o1.getX(), o1);
map.put(o2.getX(), o2);

, x- "foo", , ,

Object desiredObject = map.get("foo");

, LinkedHashMap.

0

Source: https://habr.com/ru/post/1744068/


All Articles