我对象的ArrayList,问题的indexOf [英] ArrayList of my objects, indexOf problem
问题描述
我有一个Java的ArrayList的问题。我创建了一个对象,它包含两个属性,x和y。现在,我已经装在我的ArrayList中的一些对象。问题是,我不知道如何找到为x属性附加伤害一些对象我搜索的索引。有没有办法做到这一点?
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?
推荐答案
假设是这样的:
public class Point {
public final int x;
public final int y;
}
和宣言:
List<Point> 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
}
}
请注意,这会不会给你的首页的,但是它会给你的点
本身,有时是不够的。如果你真的需要索引,那么你会希望使用索引循环,使用尺寸()
和 GET(INT指数)
(见BalusC的答案)。
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).
- Java Language Guide: the for-each loop
java.util.List
API
上述解决方案中搜索 O(N)
每个 targetX
。如果你经常这样做,那么你可以通过声明类Point工具
<一个改进此href=\"http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html\"><$c$c>Comparable<Point>$c$c>,使用 X
为主要排序键<一个href=\"http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29\"><$c$c>Collections.sort$c$c>.
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 implements
Comparable<Point>
, using x
as the primary sorting key for Collections.sort
.
然后你可以<$c$c>Collections.binarySearch$c$c>.随着 O(N日志N)
的设置时间,每个查询现在可以在回答为O(log N)
Then you can Collections.binarySearch
. With a setup time of O(N log N)
, each query can now be answered in O(log N)
.
另一种方法是使用 的SortedSet
如 TreeSet中
,特别是如果你拥有的是一个的 设置&LT;点和GT;
,而不是一个<一个href=\"http://java.sun.com/javase/6/docs/api/java/util/List.html\"><$c$c>List<Point>$c$c>.
Another option is to use a SortedSet
such as a TreeSet
, especially if what you have is a Set<Point>
, not a List<Point>
.
- How to sort an array or
ArrayList<Point>
ASC first byx
and then byy
? - Java: What is the difference between implementing Comparable and Comparator?
这篇关于我对象的ArrayList,问题的indexOf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!