Java foreach 对原语的迭代顺序是否精确定义?
示例代码:
int a[] = new int[]{0, 1, 2, 3};
int result = 0;
for (int i : a)
result += i;
循环是否保证迭代 a[0]
、a[1]
、a[2]
、a [3]
按这个顺序? 我坚信答案是肯定的,但是此页面< /a> 似乎没有明确说明顺序。
有可靠的参考吗?
Example code:
int a[] = new int[]{0, 1, 2, 3};
int result = 0;
for (int i : a)
result += i;
Is the loop guaranteed to iterate across a[0]
, a[1]
, a[2]
, a[3]
in that order? I strongly believe the answer is yes, but this page seems to not unambiguously state order.
Got a solid reference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它在 JLS< /a> 那:
相当于
It states in the JLS that:
is equivalent to
我在您引用的页面中没有找到任何暗示无序迭代的内容。 可以贴一下具体报价吗?
无论如何,我发现这段代码:
反编译为旧式循环:
当然,这与保证不同,但至少对数组进行无序迭代会非常奇怪,并且似乎违背明显的常识性实施。
I did not find anything in the page you've referenced that would imply out-of-order iteration. Can you post the specific quote?
In any case, I find that this code:
decompiles to old-style looping:
Of course, that's not the same as a guarantee, but at the very least out-of-order iteration over an array would be very weird and would seem to go against obvious common-sense implementation.
根据JLS,增强的
for 语句
,你的 for 循环相当于
“其中
array
和index
是编译器生成的标识符,它们与任何其他标识符不同(编译器生成的或其他)在增强for
语句发生处的范围内。” (这里稍微解释一下变量名)。所以是的:订单绝对有保证。
According to the JLS, The enhanced
for
statement, your for-loop is equivalent to"where
array
andindex
are compiler-generated identifiers that are distinct from any other identifiers (compiler-generated or otherwise) that are in scope at the point where the enhancedfor
statement occurs." (slightly paraphrasing the variable names here).So yes: the order is absolutely guaranteed.
请参阅 Java 语言规范第三版的 第 14.14.2 节。
See section 14.14.2 of the Java Language Specification, 3rd edition.