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?
First and foremost try to exploit the actual implementation. If it's a List
you can downcast and use better API:
if(collection instanceof List) {
((List<Foo>)collection).get(1);
}
But the "pure" solution is to create an Iterator
and call next()
two times. That's the only general interface you have:
Iterator<Foo> fooIter = collection.iterator();
fooIter.next();
Foo second = fooIter.next();
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:
Iterators.get(collection.iterator(), 1);
...or with Iterables.html#get(Iterable, int)
:
Iterables.get(collection, 1);
If you need to do this many, many times, it might be cheaper to create a copy of the collection in ArrayList
:
ArrayList<Foo> copy = new ArrayList<Foo>(collection);
copy.get(1); //second
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With