【发布时间】:2015-05-07 07:18:18
【问题描述】:
我有点好奇 values() 方法在 Java 中的 Enum 类型中是如何工作的。 正如 Java 规范文档中所见,我们可以在 for each 循环中迭代某个枚举类型的所有值。例如
for (Planet p : Planet.values()) {
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));
}
我认为每个循环都会遍历所有值。在这个调用中,我们在每个循环调用中重复调用一个方法,因此它将如何迭代所有枚举类型或 values() 方法使用某种迭代器。任何人都可以帮助我提供此方法的实现文档吗?
【问题讨论】:
-
你有什么问题?
-
"在这个调用中,我们在每个循环调用中重复调用一个方法" 不,
values()方法将被调用一次然后遍历返回的 Array。 -
看看这个 SO 答案,它详细描述了how-is-javas-for-loop-code-generated-by-the-compiler
-
@Tom
values()返回一个数组。在这种情况下没有涉及Iterable。来自 javadocReturns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows: -
@SubOptimal 是的,你是对的(编辑了该评论)。增强的 for 循环可以同时处理这两种情况:)。