我的对象的 ArrayList,indexOf 问题
我对 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设如下:
以及以下声明:
您可以使用 for-each 迭代所有点并找到您想要的点:
请注意,这不会为您提供 索引,但它会给您
Point
本身,有时这就足够了。如果您确实需要索引,那么您需要使用索引 for 循环,使用size()
和get(int index)
(请参阅 BalusC 的答案)。另请参见
java.util.List< /code> API
上述解决方案在
O(N)
中搜索每个targetX
。如果您经常这样做,那么您可以通过声明class Point Implements
Comparable
,使用x
作为Collections.sort
。
然后您可以
Collections.binarySearch
。由于设置时间为O(N log N)
,现在可以在O(log N)
内回答每个查询。另一种选择是使用
SortedSet
例如
TreeSet
,特别是如果您拥有的是设置
,而不是List
。另请参阅
x
然后按y
对数组或 ArrayListAssuming something like:
And a declaration of:
You can use for-each to iterate through all the points and find the one you want:
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, usingsize()
andget(int index)
(see BalusC's answer).See also
java.util.List
APIThe above solution searches in
O(N)
for eachtargetX
. If you're doing this often, then you can improve this by declaringclass Point implements
Comparable<Point>
, usingx
as the primary sorting key forCollections.sort
.Then you can
Collections.binarySearch
. With a setup time ofO(N log N)
, each query can now be answered inO(log N)
.Another option is to use a
SortedSet
such as aTreeSet
, especially if what you have is aSet<Point>
, not aList<Point>
.See also
ArrayList<Point>
ASC first byx
and then byy
?这是您要找的吗?
如果
:
您只想搜索 x 属性,请更改 equals 方法以仅比较 x 值,例如
Is this what you looking for?
}
}
If you just want to search on the x property, change the equals method to compare only the x values like:
只需迭代列表并测试每个元素即可。
冗长,是的,但可能直到 JDK7 带有 闭包 为止,没有其他标准方法。
Just iterate over the list and test every element.
Verbose, yes, but possibly until JDK7 with Closures, there is no other standard way.
如果我希望能够根据一个特定的属性值从集合中获取对象,我通常只使用映射。我发现这比遍历列表更干净。
现在,如果我想要 x 值为“foo”的对象,那么只要
顺序很重要,就考虑 LinkedHashMap。
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.
now, if i want the object that has an x-value of "foo", all it takes is
if order is important, consider a LinkedHashMap.