droidgren droidgren - 1 year ago 71
Java Question

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

In Java, How do I get the current index for the element in Java?

for (Element song: question){
song.currentIndex(); //<<want the current index.

In PHP you could do this:

foreach ($arr as $index => $value) {
echo "Key: $index; Value: $value";

Answer Source

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"