Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get element of Collection knowing the index? [duplicate]

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?

like image 290
Leon Kingston Avatar asked Dec 15 '22 16:12

Leon Kingston


1 Answers

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
like image 137
Tomasz Nurkiewicz Avatar answered Jan 17 '23 22:01

Tomasz Nurkiewicz