<分区>
Possible Duplicate:
best way to get value from Collection by index
假设我有一个 Collection
.我需要获取索引 2 处的元素。
如果没有 get 方法并且迭代器不跟踪索引,我该怎么做?
标签 java collections
<分区>
Possible Duplicate:
best way to get value from Collection by index
假设我有一个 Collection
.我需要获取索引 2 处的元素。
如果没有 get 方法并且迭代器不跟踪索引,我该怎么做?
最佳答案
首先尝试利用实际的实现。如果它是一个 List
,你可以向下转换并使用更好的 API:
if(collection instanceof List) {
((List<Foo>)collection).get(1);
}
但“纯粹”的解决方案是创建一个Iterator
并调用next()
两次。这是您拥有的唯一通用界面:
Iterator<Foo> fooIter = collection.iterator();
fooIter.next();
Foo second = fooIter.next();
这可以很容易地推广到第 k 个元素。但是不用担心,已经有一个方法可以解决这个问题:Iterators.html#get(Iterator, int)
在 Guava 中:
Iterators.get(collection.iterator(), 1);
...或使用 Iterables.html#get(Iterable, int)
:
Iterables.get(collection, 1);
如果您需要多次执行此操作,在 ArrayList
中创建集合的副本可能会更便宜:
ArrayList<Foo> copy = new ArrayList<Foo>(collection);
copy.get(1); //second
关于java - 获取知道索引的 Collection 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13691643/