Use a traditional loop. For-each statements in java do not promise an order over the collection. The only way to actually know the index is to query the list on every iteration.
for(int i=0; i<list.size; i++){
// you have your index, i
// the item is at list.get(i)
}
Relying on the iterator() implementation you can also use an alternative (+1 Zak in the comments):
int position = 0;
for(Item i : list){
// do stuff with `i`
// increase position as the last action in the loop
position++;
}
From the docs: Iterator<E> iterator() Returns an iterator over the elements in this list in proper sequence
Here is why I usually don't use the short form of for
:
import java.util.ArrayList;
import java.util.Iterator;
public class MyList<T> extends ArrayList<T> {
// the main function to run the example
public static void main(String[] args){
// make a list of my special type
MyList<Integer> list = new MyList<Integer>();
// add 10 items to it
for (int i =0; i<10; i++){
list.add(i);
}
// print the list using the for-each mechanism (it's actually an iterator...)
for (Integer i : list){
System.out.println(i);
}
}
// I like lists that start at 3!
// make my list return an iterator in the middle of the list...
@Override
public Iterator<T> iterator(){
return this.listIterator(3);
}
}
Obviously, you'd expect having the first item on the first iteration, and this is clearly not the case because an iterator can be implemented in many ways and Java's foreach
is depending on the underlying iterator
implemetation.
Also, you have to use position++
in the end of your loop which is probably error-prone (don't know, don't usually use it..).
That said, it does improve readability like mentioned in this stackoverflow question about Java's foreach.
For more information, see How does the Java for each loop work?.