Can anybody tell me how to print the index number of elements in the ArrayList using for each looping in Java.
like @Michael's but shorter. A pet obsession I'll admit.
List<String> list = Arrays.asList("zero", "one", "two", "three");
int index=0;
for(String s : list)
System.out.println((index++)+": "+s);
prints
0: zero
1: one
2: two
3: three
You have to keep track of the index numbers yourself, as you loop through the ArrayList. The List iterator won't do that for you.
You'd normally do that through a separate variable. You could store objects with an associated index, but you'd have to be sure to maintain ordering (by not deleting, resorting etc.)
By keeping a separate index count:
int index=0;
for(String s : list){
System.out.println(String.valueOf(index++)+": "+s);
}
Probably makes more sense to use a regular for loop instead. The "enhanced for loop" is based on the Iterable
and Iterator
interfaces - it doesn't know anything about implementation details of the underlying collection (which may well not have an index for each element).
You'll need to either iterate with an integer index, or keep a counter going.
List<kind> aList;
...
int index = 0;
for(kind x : aList)
{
...
index++;
}
or
for(int index = 0; index < aList.size(); index++)
{
Kind x = aList.get(index)
...
}