I am using an Iterator to iterate through a collection and I want to get the current element's index.
How can I do that?
I am using an Iterator to iterate through a collection and I want to get the current element's index.
How can I do that?
Though you already had the answer, thought to add some info.
As you mentioned Collections explicitly, you can't use listIterator to get the index for all types of collections.
List interfaces - ArrayList, LinkedList, Vector and Stack.
Has both iterator() and listIterator()
Set interfaces - HashSet, LinkedHashSet, TreeSet and EnumSet.
Has only iterator()
Map interfaces - HashMap, LinkedHashMap, TreeMap and IdentityHashMap
Has no iterators, but can be iterated using through the keySet() / values() or entrySet() as keySet() and entrySet() returns Set and values() returns Collection.
So its better to use iterators() with continuous increment of a value to get the current index for any collection type.