有没有办法在 Java 的 for-each 循环中访问迭代计数器? [英] Is there a way to access an iteration-counter in Java's for-each loop?

查看:32
本文介绍了有没有办法在 Java 的 for-each 循环中访问迭代计数器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆