编辑:@StephenC是对的,JLS是一个更好的地方找到这种性质的答案。语言规范中有一个link to the enhanced for loop。在那里你会发现它有几种不同类型的for语句,但它们都不会超过1次调用这个方法。
简单测试表明,该方法只调用一次
public class TestA {
public String [] theStrings;
public TestA() {
theStrings = new String[] {"one","two", "three"};
for(String string : getTheStrings()) {
System.out.println(string);
}
}
public String[] getTheStrings() {
System.out.println("get the strings");
return theStrings;
}
public static void main(String [] args) {
new TestA();
}
}
输出:
get the strings
one
two
three
所以基本上他们是同样的事情。如果你想在for循环之外使用数组,唯一可能对2nd有利的是。
编辑
你让我好奇的处理上面我会这样使用的代码Java编译器如何反编译的类文件和继承人的结果是什么
public class TestA
{
public TestA()
{
String as[];
int j = (as = getTheStrings()).length;
for(int i = 0; i < j; i++)
{
String string = as[i];
System.out.println(string);
}
}
public String[] getTheStrings()
{
System.out.println("get the strings");
return theStrings;
}
public static void main(String args[])
{
new TestA();
}
public String theStrings[] = {
"one", "two", "three"
};
}
,你可以看到编译器简单地将你的for循环重构为一个标准循环!它也进一步证明,实际上它们在编译器完成之后完全相同。
它只被调用一次,但第二个版本太冗长了。你正在做的是通过一个列表。一条线就够了。 – Navin