在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循环中有这样一个计数器的唯一方法是什么?
在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循环中有这样一个计数器的唯一方法是什么?
当前回答
最佳和优化的解决方案是做以下事情:
int i=0;
for(Type t: types) {
......
i++;
}
其中Type可以是任何数据类型,types是应用于循环的变量。
其他回答
我通常使用数组来解决这个问题
List<String> list = new ArrayList<String>();
final int[] counter = new int[1];
list.foreach( item -> {
list.get(counter[0]) // code here that can use counter[0] for counter value
counter[0]++; // increment the counter
}
Sun正在为Java7考虑的一个变化是在foreach循环中提供对内部迭代器的访问。语法将是这样的(如果这是接受的):
for (String str : list : it) {
if (str.length() > 100) {
it.remove();
}
}
这是语法上的甜食,但显然有很多人对这个功能提出了要求。但是在它被批准之前,您必须自己计算迭代次数,或者使用带有Iterator的常规for循环。
pax的答案有一个“变体”…: -)
int i = -1;
for(String s : stringArray) {
doSomethingWith(s, ++i);
}
对于偶尔需要索引的情况,比如在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);
}
}
还有另一种方法。
如果您编写了自己的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++); }
...
}
}
}
}
}