问题描述
我为数组列表编写了一个简单的 for 循环检索
int[] a = new int[5] ;
for(int d:a)
{
Arrays.fill(a,111);
System.out.print(d);
}
我就是不知道那个 0 在做什么。我的预期输出是 111111111111
。
当我使用简单的 for 循环编写相同的代码时
int[] a = new int[5] ;
for(int i=0;i<a.length;i++)
{
Arrays.fill(a,111);
System.out.print(a[i]);
}
它符合我的期望。我想知道我错在哪里。
解决方法
这个 answer 最后解释了,对于数组,增强的 for-each 与使用带有计数器的传统 for 循环“基本上”相同。
但本质区别是:增强的 for 循环必须选择第一个数组条目,将其放入d
变量中,之前循环正文已输入。
在您的第二个示例中,没有 值在数组更新之前 从数组中检索到。在第一个示例中,在数组填充 1 之前检索(然后打印)一个值。
这就是全部。
,查看 the language spec 以了解增强的 for 循环的说明。
对于数组,它表示等效的基本 for 循环是:
// This loop...
for (TargetType Identifier : Expression) {
Statement
}
// ...is equivalent to this:
T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
{VariableModifier} TargetType Identifier = #a[#i];
Statement
}
将您的第一个循环替换为:
// T[] #a = Expression;
T[] aa = a;
// You have no labels,so no need for the L1: L2 line.
// for (int #i = 0; #i < #a.length; #i++) {
for (int i = 0; i < aa.length; ++i) {
// {VariableModifier} TargetType Identifier = #a[#i];
int d = aa[i];
// Statement is your loop body:
Arrays.fill(a,111);
System.out.print(d);
}
如果你这样看,你可以看到在 d
语句之前分配了 Arrays.fill(a,111);
。因此,d
不受 fill
的影响。
第一个相当于:
int[] a = new int[5] ;
for(int i=0; i< a.length; i++)
{
int d=a[i];
Arrays.fill(a,111);
System.out.print(d);
}