Java, How do I get current index/key in "for each" loop

This question already has an answer here:

  • Is there a way to access an iteration-counter in Java's for-each loop? 14 answers

  • You can't, you either need to keep the index separately:

    int index = 0;
    for(Element song : question) {
        System.out.println("Current index is: " + (index++));
    }
    

    or use a normal for loop:

    for(int i = 0; i < question.length; i++) {
        System.out.println("Current index is: " + i);
    }
    

    The reason is you can use the condensed for syntax to loop over any Iterable, and it's not guaranteed that the values actually have an "index"


    for (Song s: songList){
        System.out.println(s + "," + songList.indexOf(s); 
    }
    

    it is possible in linked list.

    you have to make toString() in song class. if you don't it will print out reference of the song.

    probably irrelevant for you by now. ^_^


    In Java, you can't, as foreach was meant to hide the iterator. You must do the normal For loop in order to get the current iteration.

    链接地址: http://www.djcxy.com/p/52972.html

    上一篇: 在C#中的foreach循环中计数器

    下一篇: Java,我如何获得当前的索引/键“为每个”循环