我目前正在阅读 Downey 的 Think Java,其中最近介绍了增强的 for 循环。有人提到,增强的 for 循环在遍历数组时不考虑元素索引。我认为这不会阻止类似以下方法的工作:
public static double[] powArray(double[] a) {
for (double value : a) {
value = Math.pow(value, 2.0);
}
return a;
}
但是,似乎确实如此(它所属的其余代码似乎很好)。请注意,当我运行以下命令时,此方法最终返回相同的数组:
System.out.println(Arrays.toString(powArray(a)));
我想我无法理解这里的问题是否在于我如何处理增强的 for 循环或数组引用。 提前致谢!
最佳答案
查看JLS Sec 14.14.2 ,其中给出了数组上增强的 for 循环的等效形式:
for ( {VariableModifier} TargetType Identifier : Expression ) Statement
[is equivalent to, if
Expression
is an array type]T[] #a = Expression; L1: L2: ... Lm: for (int #i = 0; #i < #a.length; #i++) { {VariableModifier} TargetType Identifier = #a[#i]; Statement }
因此,编译器将您的循环转换为如下所示:
double[] a = arr;
for (int i = 0; i < a.length; i++) {
double value = a[i];
value = Math.pow(value, 2.0);
}
您正在对 value
进行平方,但该值永远不会写回 arr
(甚至是 a
)。
如果要修改数组元素,则必须显式使用基本的 for 循环:
for (int i = 0; i < a.length; i++) {
a[i] = Math.pow(a[i], 2.0);
}
关于java - 增强for循环遍历Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43813104/