gpt4 book ai didi

java - 为什么我可以在 Java 的 forEach 循环中迭代数组?

转载 作者:行者123 更新时间:2023-12-02 08:52:31 28 4
gpt4 key购买 nike

通常的想法是,如果某个结构不可迭代,我就无法使用 forEach 迭代该结构。但为什么我可以在 Java 中迭代数组呢?数组不是可迭代

MyClass[] array = {new MyClass("a"), new MyClass("b")};

for (MyClass c : array) {
System.out.println(c);
}

最佳答案

原因是language has made an allowance为了它。虽然它可能以不同的方式表示两个对象,但迭代的顺序是相同的 - 并且效果对您来说是透明的。

...Otherwise, the Expression necessarily has an array type, T[].

Let L1 ... Lm be the (possibly empty) sequence of labels immediately preceding the enhanced for statement.

The enhanced for statement is equivalent to a basic for statement of the form:

T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
VariableModifiersopt TargetType Identifier = #a[#i];
Statement
}

#a and #i are automatically generated identifiers that are distinct from any other identifiers (automatically generated or otherwise) that are in scope at the point where the enhanced for statement occurs.

TargetType is the type of the loop variable as denoted by the Type that appears in the FormalParameter followed by any bracket pairs that follow the Identifier in the FormalParameter (§10.2).

关于java - 为什么我可以在 Java 的 forEach 循环中迭代数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27256724/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com