Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print the index number of elements in the ArrayList using for each looping

Tags:

java

list

Can anybody tell me how to print the index number of elements in the ArrayList using for each looping in Java.

like image 309
Dorji Avatar asked Dec 09 '22 11:12

Dorji


2 Answers

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 image 144
Michael Borgwardt Avatar answered Dec 11 '22 23:12

Michael Borgwardt


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
like image 32
Peter Lawrey Avatar answered Dec 12 '22 00:12

Peter Lawrey