问题引出

事情的起因是我用增强for循环为数组赋值,发现赋值一直无效

1
2
3
4
5
6
7
8
9
10
11
12
Random random = new Random();
int[] arrays = new int[10];
// 使用增强for循环赋值
for (int array : arrays) {
array = random.nextInt(100);
}
// 使用增强for循环遍历
for (int array : arrays) {
System.out.print(array + " ");
}
// 输出结果
// 0 0 0 0 0 0 0 0 0 0

对,无论试了多少次,以上结果还是10个0

参考文章,恍然大悟

于是参考了这篇文章,解答了我的困惑

java增强型for报错_一个Java增强型for循环的易犯错误,你注意到了吗?_就浙就浙就浙的博客-CSDN博客

总结失败原因

基本数据类型数组情况

使用增强for循环赋值数组失败原因

1
2
3
for (int array : arrays) {
array = random.nextInt(100);
}

上面这段代码,每次从arrays中取出一个元素,赋给局部变量array,这个过程是值传递,不是引用传递,因此array是arrays数组元素的一个副本,无论怎么改变array的数值大小,都无法影响到arrays数组,因此就会赋值失败

由此看来:增强for循环更适合用来遍历数组

遍历包装类情况

和遍历基本数据类型的数组一样,增强for循环用在包装类上和基本数据类型数组一样,赋值操作会失败

1
2
3
4
5
6
7
8
9
10
11
12
Random random = new Random();
Integer[] arrays = new Integer[10];
// 使用增强for循环赋值
for (Integer array : arrays) {
array = random.nextInt(100);
}
// 使用增强for循环遍历
for (Integer array : arrays) {
System.out.print(array + " ");
}
// 结果
// null null null null null null null null null null

其他引用传递情况

这种情况增强for循环就可以修改对应数组元素的值,如遍历对象数组等等

正确姿势

1
2
3
4
5
6
7
8
9
10
11
12
Random random = new Random();
Integer[] arrays = new Integer[10];
// 使用普通for循环赋值
for (int i = 0; i < arrays.length; i++) {
arrays[i] = random.nextInt(100);
}
// 使用增强for循环遍历
for (Integer array : arrays) {
System.out.print(array + " ");
}
// 结果
// 7 9 68 4 87 79 63 49 55 2