在Java中,我如何获得Java元素的当前索引?
for (Element song: question){
song.currentIndex(); //<<want the current index.
}
在PHP中,你可以这样做:
foreach ($arr as $index => $value) {
echo "Key: $index; Value: $value";
}
在Java中,我如何获得Java元素的当前索引?
for (Element song: question){
song.currentIndex(); //<<want the current index.
}
在PHP中,你可以这样做:
foreach ($arr as $index => $value) {
echo "Key: $index; Value: $value";
}
当前回答
你不能,你需要单独保存索引:
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,并且不能保证这些值实际上有一个“索引”。
其他回答
来自我正在使用的当前代码的示例:
int index=-1;
for (Policy rule : rules)
{
index++;
// do stuff here
}
让您从0的索引开始,并在处理过程中递增。
在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++;
}
希望对大家有所帮助:)
你不能,你需要单独保存索引:
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,并且不能保证这些值实际上有一个“索引”。
正如其他人指出的,“不可能直接”。 我猜你想要某种歌曲的索引键? 只需在Element中创建另一个字段(成员变量)。将Song添加到集合时增加它。
在Java中,不能这样做,因为foreach是用来隐藏迭代器的。为了得到当前的迭代,您必须执行普通的For循环。