java 我的对象的 ArrayList,indexOf 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2769797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:44:21  来源:igfitidea点击:

ArrayList of my objects, indexOf problem

javaobjectarraylistindexof

提问by majtits

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 know how to find index of some object with x atribute I'm searching. Is there any way to do this?

我对 Java 的 ArrayList 有问题。我创建了一个对象,它包含两个属性,x 和 y。现在我已经在我的 ArrayList 中加载了一些对象。问题是我不知道如何使用我正在搜索的 x 属性找到某个对象的索引。有没有办法做到这一点?

回答by polygenelubricants

Assuming something like:

假设类似:

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

And a declaration of:

并声明:

List<Point> points = ...;

You can use for-each to iterate through all the points and find the one you want:

您可以使用 for-each 遍历所有点并找到您想要的点:

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

请注意,这不会为您提供index,但它会给您Point本身,这有时就足够了。如果你真的需要索引,那么你会想要使用索引 for 循环,使用size()get(int index)(参见 BalusC 的答案)。

See also

也可以看看



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<Point>, using xas the primary sorting key for Collections.sort.

上述解决方案搜索O(N)每个targetX. 如果您经常这样做,那么您可以通过声明class Point implementsComparable<Point>,x用作 的主要排序键来改进这一点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).

那么你可以Collections.binarySearch。设置时间为 时O(N log N),现在可以在 中回答每个查询O(log N)

Another option is to use a SortedSetsuch as a TreeSet, especially if what you have is a Set<Point>, not a List<Point>.

另一种选择是使用SortedSet诸如a 之类的TreeSet,特别是如果您拥有的是 aSet<Point>而不是 a List<Point>

See also

也可以看看

回答by Suresh Kumar

Is this what you looking for?

这是你要找的吗?

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));
}

}

}

If you just want to search on the x property, change the equals method to compare only the x values like:

如果您只想搜索 x 属性,请更改 equals 方法以仅比较 x 值,例如:

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

}

回答by BalusC

Just iterate over the list and test every element.

只需遍历列表并测试每个元素。

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

Verbose, yes, but possibly until JDK7 with Closures, there is no other standard way.

详细,是的,但可能直到带有Closures 的JDK7 ,没有其他标准方法。

回答by rompetroll

I usually just use a map if i want to be able to fetch an object out of a collection based on one specific attribute value. I find that cleaner than having to iterate over lists.

如果我希望能够根据一个特定的属性值从集合中获取对象,我通常只使用地图。我发现这比遍历列表更干净。

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

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

now, if i want the object that has an x-value of "foo", all it takes is

现在,如果我想要 x 值为“foo”的对象,只需要

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

if order is important, consider a LinkedHashMap.

如果顺序很重要,请考虑使用 LinkedHashMap。