有没有办法在 Java 的 for-each 循环中访问迭代计数器? [英] Is there a way to access an iteration-counter in Java's for-each loop?
问题描述
Java 的 for-each 循环有没有办法
Is there a way in Java's for-each loop
for(String s : stringArray) {
doSomethingWith(s);
}
找出循环已经被处理的频率?
to find out how often the loop has already been processed?
除了使用旧的和众所周知的for(int i=0; i
Aside from using the old and well-known for(int i=0; i < boundary; i++)
- loop, is the construct
int i = 0;
for(String s : stringArray) {
doSomethingWith(s);
i++;
}
在 for-each 循环中使用这样一个计数器的唯一方法是什么?
the only way to have such a counter available in a for-each loop?
推荐答案
不需要,但您可以提供自己的计数器.
No, but you can provide your own counter.
这样做的原因是for-each循环内部没有计数器;它基于 Iterable 接口,即它使用 Iterator
循环遍历集合"——它可能根本不是一个集合,实际上可能根本不是基于索引的东西(例如链表).
The reason for this is that the for-each loop internally does not have a counter; it is based on the Iterable interface, i.e. it uses an Iterator
to loop through the "collection" - which may not be a collection at all, and may in fact be something not at all based on indexes (such as a linked list).
这篇关于有没有办法在 Java 的 for-each 循环中访问迭代计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!