4

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?

Community
  • 1
  • 1
Leon Kingston
  • 73
  • 1
  • 1
  • 6

1 Answers1

12

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
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674