Can anybody tell me how to print the index number of elements in the ArrayList using for each looping in Java.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With