有没有办法在Java的for-each循环中访问迭代计数器? [英] Is there a way to access an iteration-counter in Java's for-each loop?
问题描述
在Java的for-each循环中有没有一种方法?
for(String s:stringArray){
doSomethingWith (一个或多个);
}
找出循环已经被处理了多久?
除了使用旧的和众所周知的(int i = 0; i< boundary; i ++)
- loop,是构造
int i = 0;
for(String s:stringArray){
doSomethingWith(s);
i ++;
$ b $ p
$ b $ p $是唯一可以在for-each循环中使用这种计数器的方法吗?不过,你可以提供自己的计数器。
原因在于for-each循环内部没有 一个计数器;它基于 Iterable 界面,即它使用一个 Iterator
来循环集合 - 这可能根本不是一个集合,实际上可能根本不是基于索引的东西(比如作为一个链表)。
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?
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++;
}
the only way to have such a counter available in a for-each loop?
解决方案 No, but you can provide your own counter.
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屋!