Java,如何在“for each”循环中获取当前索引/键

2022-08-31 05:12:54

在Java中,如何获取Java中元素的当前索引?

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

在 PHP 中,你可以这样做:

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

答案 1

您不能,或者需要单独保留索引:

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

或使用正常的 for 循环:

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

原因是您可以使用压缩的语法来循环访问任何可迭代对象,并且不能保证值实际上具有“索引”


答案 2

在Java中,你不能,因为foreach是为了隐藏迭代器。必须执行正常的 For 循环才能获取当前迭代。


推荐