我有以下代码:
for (Attribute thisAttribute : factor.getAttributes()) {
// blabla
}
哪里factor.getAttributes()
返回 List<Attribute>
.
显然,只有一次对 factor.getAttributes()
的初始调用然后开始遍历。但是,我不明白为什么只有一个电话。如果我要在常规 for()
的 header 中包含一个函数调用循环,我相信它会在每次迭代时被评估。在这方面,高级循环有何不同以及为何不同?
最佳答案
把它想象成被翻译成类似的东西:
{
Iterator<Attribute> it = factor.getAttributes().iterator();
while (it.hasNext()) {
Attribute thisAttribute = it.next();
// loop body here
}
}
编译器知道它获得了一个 Iterable,它可以从中获得 Iterator 一次并在循环中使用它。
事实证明 Java language specification似乎同意,它说:
The enhanced for statement is equivalent to a basic for statement of the form:
for (I #i = Expression.iterator(); #i.hasNext(); ) {
{VariableModifier} TargetType Identifier =
(TargetType) #i.next();
Statement
}
关于Java 高级循环 : what is (not) evaluated in the loop's header?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25810350/