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

前端 未结 4 2006
一整个雨季
一整个雨季 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 11:56

    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
    
    0 讨论(0)
  • 2021-01-22 11:56

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

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-22 12:02

    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)
    ...
    }
    
    0 讨论(0)
提交回复
热议问题