Java,我如何获得当前索引/键在“;为每个”;循环

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

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

在PHP中,你可以这样做:

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

在Java中,不能这样做,因为foreach是用来隐藏迭代器的。为了得到当前的迭代,您必须执行普通的For循环。

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

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语法来遍历任何可迭代的,并且不能保证这些值实际上有一个“索引”

跟踪你的索引:在Java中就是这样做的:

 int index = 0;
for (Element song: question){
// Do whatever
index++;
}

在Java中是不可能的。


Scala是这样的:

val m = List(5, 4, 2, 89)


for((el, i) <- m.zipWithIndex)
println(el +" "+ i)

在Java中,你需要运行简单的“for”;循环或使用一个额外的整数来跟踪索引,例如:

int songIndex = 0;
for (Element song: album){
// Do whatever
songIndex++;
}

希望对大家有所帮助:)

正如其他人指出的,“不可能直接”。 我猜你想要某种歌曲的索引键? 只需在Element中创建另一个字段(成员变量)。当你将Song添加到集合时增加它

来自我正在使用的当前代码的示例:

int index=-1;
for (Policy rule : rules)
{
index++;
// do stuff here
}

让您从0的索引开始,并在处理过程中递增。