在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是应用于循环的变量。
其他回答
如果你在for-each循环中需要一个计数器,你就必须数自己。据我所知,没有内置的计数器。
恐怕foreach不行。但我可以给你一个简单的老式for循环:
List<String> l = new ArrayList<String>();
l.add("a");
l.add("b");
l.add("c");
l.add("d");
// the array
String[] array = new String[l.size()];
for(ListIterator<String> it =l.listIterator(); it.hasNext() ;)
{
array[it.nextIndex()] = it.next();
}
注意,List接口允许您访问它。nextindex()。
(编辑)
到你改变的例子:
for(ListIterator<String> it =l.listIterator(); it.hasNext() ;)
{
int i = it.nextIndex();
doSomethingWith(it.next(), i);
}
我有点惊讶没有人提出以下建议(我承认这是一个懒惰的方法…); 如果stringArray是某种类型的List,您可以使用类似stringArray. indexof (S)的东西来返回当前计数的值。
注意:这假设List的元素是唯一的,或者它们是否非唯一并不重要(因为在这种情况下,它将返回找到的第一个副本的索引)。
在某些情况下,这就足够了……
下面是我如何做到这一点的一个例子。这将获得每个循环的索引。希望这能有所帮助。
public class CheckForEachLoop {
public static void main(String[] args) {
String[] months = new String[] { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST",
"SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };
for (String s : months) {
if (s == months[2]) { // location where you can change
doSomethingWith(s); // however many times s and months
// doSomethingWith(s) will be completed and
// added together instead of counter
}
}
System.out.println(s);
}
}
pax的答案有一个“变体”…: -)
int i = -1;
for(String s : stringArray) {
doSomethingWith(s, ++i);
}