Possible Duplicate:
best way to get value from Collection by index
Say I have a Collection
. And I need to get the element at index 2.
How would I do this if there's no get method and iterator doesn't track indexes?
collectionsjava
Possible Duplicate:
best way to get value from Collection by index
Say I have a Collection
. And I need to get the element at index 2.
How would I do this if there's no get method and iterator doesn't track indexes?
Best Answer
First and foremost try to exploit the actual implementation. If it's a
List
you can downcast and use better API:But the "pure" solution is to create an
Iterator
and callnext()
two times. That's the only general interface you have:This can be easily generalized to k-th element. But don't bother, there is already a method for that:
Iterators.html#get(Iterator, int)
in Guava:...or with
Iterables.html#get(Iterable, int)
:If you need to do this many, many times, it might be cheaper to create a copy of the collection in
ArrayList
: