在Java的for-each循环中有办法吗

for(String s : stringArray) {
  doSomethingWith(s);
}

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

除了使用老的和众所周知的for(int i=0;I <边界;i++) - loop,是构造

int i = 0;
for(String s : stringArray) {
  doSomethingWith(s);
  i++;
}

在for-each循环中有这样一个计数器的唯一方法是什么?


当前回答

对于偶尔需要索引的情况,比如在catch子句中,我有时会使用indexOf。

for(String s : stringArray) {
  try {
    doSomethingWith(s);
  } catch (Exception e) {
    LOGGER.warn("Had some kind of problem with string " +
      stringArray.indexOf(s) + ": " + s, e);
  }
}

其他回答

惯用的解决方案:

final Set<Double> doubles; // boilerplate
final Iterator<Double> iterator = doubles.iterator();
for (int ordinal = 0; iterator.hasNext(); ordinal++)
{
    System.out.printf("%d:%f",ordinal,iterator.next());
    System.out.println();
}

这实际上是谷歌在关于为什么他们不提供CountingIterator的讨论中提出的解决方案。

没有,但你可以提供自己的柜台。

这样做的原因是for-each循环内部没有计数器;它基于Iterable接口,也就是说,它使用一个迭代器来遍历“集合”——这可能根本不是一个集合,实际上可能根本不是基于索引的东西(比如链表)。

如果你在for-each循环中需要一个计数器,你就必须数自己。据我所知,没有内置的计数器。

还有另一种方法。

如果您编写了自己的Index类和一个静态方法,该方法在该类的实例上返回Iterable,那么您可以

for (Index<String> each: With.index(stringArray)) {
    each.value;
    each.index;
    ...
}

其中实现With。索引是这样的

class With {
    public static <T> Iterable<Index<T>> index(final T[] array) {
        return new Iterable<Index<T>>() {
            public Iterator<Index<T>> iterator() {
                return new Iterator<Index<T>>() {
                    index = 0;
                    public boolean hasNext() { return index < array.size }
                    public Index<T> next() { return new Index(array[index], index++); }
                    ...
                }
            }
        }
    }
}

对于偶尔需要索引的情况,比如在catch子句中,我有时会使用indexOf。

for(String s : stringArray) {
  try {
    doSomethingWith(s);
  } catch (Exception e) {
    LOGGER.warn("Had some kind of problem with string " +
      stringArray.indexOf(s) + ": " + s, e);
  }
}