在Java中,如何获取Java中元素的当前索引?
for (Element song: question){
song.currentIndex(); //<<want the current index.
}在PHP中,你可以这样做:
foreach ($arr as $index => $value) {
echo "Key: $index; Value: $value";
}发布于 2010-08-08 02:24:52
你不能,你要么需要单独保存索引:
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);
}这是因为您可以使用精简的for语法在任何索引上循环,并且不能保证这些值确实具有“Iterable”。
发布于 2010-08-08 02:24:27
在Java中,你不能这样做,因为foreach的目的是隐藏迭代器。您必须执行普通的For循环才能获得当前迭代。
发布于 2010-08-08 02:56:17
跟踪索引:Java中就是这样做的:
int index = 0;
for (Element song: question){
// Do whatever
index++;
}https://stackoverflow.com/questions/3431529
复制相似问题