有没有办法在Java的for-each循环中访问迭代计数器?

在Java的for-each循环中是否有一种方法


for(String s : stringArray) {

  doSomethingWith(s);

}

找出循环已经处理的频率?


除了使用旧的和众所周知的for(int i=0; i < boundary; i++)循环之外,还有构造


int i = 0;

for(String s : stringArray) {

  doSomethingWith(s);

  i++;

}

在for-each循环中使用这种计数器的唯一方法是什么?


浮云间
浏览 548回答 3
3回答

繁华开满天机

还有另一种方式。鉴于您编写自己的Index类和静态方法,可以返回Iterable此类的实例for (Index<String> each: With.index(stringArray)) {&nbsp; &nbsp; each.value;&nbsp; &nbsp; each.index;&nbsp; &nbsp; ...}执行的地方With.index是什么样的class With {&nbsp; &nbsp; public static <T> Iterable<Index<T>> index(final T[] array) {&nbsp; &nbsp; &nbsp; &nbsp; return new Iterable<Index<T>>() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public Iterator<Index<T>> iterator() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new Iterator<Index<T>>() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; index = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public boolean hasNext() { return index < array.size }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public Index<T> next() { return new Index(array[index], index++); }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java