2012-12-03 76 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