Java 高级循环 : what is (not) evaluated in the loop's header?

标签 java loops

我有以下代码:

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/

相关文章:

java - 在 JBOSS EAP 6.3 上部署 REST Webservice 时出错

java - 如何检查从数据库中获取的 double 值是否为空值

python - Pandas 只删除连续重复的行,忽略特定的列

php - WordPress 自定义帖子类型分类法 - 获取特定内容

java - 将 Oracle 日期算术转换为在 HSQLDB 中工作

java - notify() 在 Runnable 中不起作用

c - 输入用户的密码并检查它是否包含字符、字母和数字

c++ - 循环中的条件评估?

java - 如何在字符串中查找与正则表达式模式不匹配的字符

python - 在500 HTTP服务器错误后重试,从文件中使用的最后一行继续