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

前端 未结 4 2055
一整个雨季
一整个雨季 2021-01-22 11:36

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

4条回答
  •  感动是毒
    2021-01-22 12:01

    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).

提交回复
热议问题