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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First and foremost try to exploit the actual implementation. If it’s a
Listyou can downcast and use better API:But the “pure” solution is to create an
Iteratorand 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: