为什么java中有两种不同的for循环? [英] why are there two different kinds of for loops in java?
问题描述
我有一个 for 循环,但我不确定它是如何工作的.我熟悉:
I have a for loop, and I am not sure how it works. I am familiar with:
for(int i = 0; i <= 9; i++)
{
/* implementation */
}
我对以下形式的 for 循环感到困惑:
I am confused about a for loop in the following form:
String[] myString = new String[] {"one", "two", "three", "some other stuff"};
String str1 = "", str2 = "";
for (String s : myString)
{
/* implementation */
}
这些类型的 for
循环如何工作?它们与常规 for
循环有何不同?
How do these types of for
loops work? what do they do differently then regular for
loops?
推荐答案
第一个是原来的 for 循环.你初始化一个变量,设置一个终止条件,并提供一个状态递增/递减计数器(有例外,但这是经典)
The first is the original for loop. You initialize a variable, set a terminating condition, and provide a state incrementing/decrementing counter (There are exceptions, but this is the classic)
为此,
for (int i=0;i<myString.length;i++) {
System.out.println(myString[i]);
}
是正确的.
对于 Java 5,提出了一个替代方案.任何实现 iterable 的东西都可以得到支持.这在 Collections 中特别好.例如,您可以像这样迭代列表
For Java 5 an alternative was proposed. Any thing that implements iterable can be supported. This is particularly nice in Collections. For example you can iterate the list like this
List<String> list = ....load up with stuff
for (String string : list) {
System.out.println(string);
}
代替
for (int i=0; i<list.size();i++) {
System.out.println(list.get(i));
}
所以它实际上只是一种替代符号.任何实现 Iterable(即可以返回迭代器)的项都可以这样编写.
So it's just an alternative notation really. Any item that implements Iterable (i.e. can return an iterator) can be written that way.
幕后发生的事情是这样的:(效率更高,但我写得很明确)
What's happening behind the scenes is somethig like this: (more efficient, but I'm writing it explicitly)
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String string=it.next();
System.out.println(string);
}
最后它只是语法糖,但相当方便.
In the end it's just syntactic sugar, but rather convenient.
这篇关于为什么java中有两种不同的for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!