Java,如何在“for each”中获取当前索引/键。环 [英] Java, How do I get current index/key in "for each" loop

查看:169
本文介绍了Java,如何在“for each”中获取当前索引/键。环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

在PHP中你可以这样做:

In PHP you could do this:

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


推荐答案

你不能,你要么需要单独保留索引:

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++));
}

或使用正常for循环:

or use a normal for loop:

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

原因是您可以使用精简语法循环任何 Iterable ,并不保证值实际上有一个索引

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"

这篇关于Java,如何在“for each”中获取当前索引/键。环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆