2012-12-03 78 views
2

可能重复:
best way to get value from Collection by index获取知道索引的Collection元素?

说我有一个Collection。我需要得到索引2的元素。

如果没有get方法并且迭代器不跟踪索引,我该怎么做?

+1

集合只是一个接口,您正在使用哪个集合? – clavio

+2

除非你有一个有序列表或一个有序集合,否则在索引2处获取一个元素可能没有意义。 –

+0

Perhpas如果你想保留订单,最好使用一个列表。 – Pablo

回答

9

首先尝试利用实际的实现。如果它是一个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)番石榴:

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