java - 在 java 增强的 for 循环中,假设要循环的表达式只被评估一次是否安全?

标签 java

在以下内容中:

for (String deviceNetwork : deviceOrganizer.getNetworkTypes(deviceManufacturer)) {
    // do something
}

假设 deviceOrganizer.getNetworkTypes(deviceManufacturer) 只会被调用一次是否安全?

最佳答案

是的,绝对。

来自 section 14.14.2 of the spec :

If the type of Expression is a subtype of Iterable, then let I be the type of the expression Expression.iterator(). The enhanced for statement is equivalent to a basic for statement of the form:

for (I #i = Expression.iterator(); #i.hasNext(); ) {
        VariableModifiersopt Type Identifier = #i.next();
   Statement
}

(另一种方法处理数组。)

请注意 Expression 仅在 for 循环表达式的第一部分中提及 - 因此它仅被计算一次。

关于java - 在 java 增强的 for 循环中,假设要循环的表达式只被评估一次是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2686588/

相关文章:

java - 在 Swing 中使用仿射变换将字体大小设置为与其容器成比例

java - 如何超出get方法的返回字符串(httpurlconnection)

java - 无法从 POJO 生成 Json 架构

java - <html :html></html:html> and <html></html> 之间的区别

代理后面的 Java 应用程序在 Linux 中使用 http_proxy 变量

java - 如何在第二个 JSF 项目中运行一个 JSF WAR 文件?

java - 在框架内打开 https 页面是否存在问题

java - 无法在 onComplete 方法中设置适配器 Facebook SDK,ANDROID

java - 如何处理应该有很多异常(exception)的情况?

java - Cucumber CDI 注入(inject)不适用于 src/main/java 中的 bean