在以下内容中:
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/