当我使用普通的 for 循环时,
数组中的所有元素都会正常初始化:
Object[] objs = new Object[10];
for (int i=0;i<objs.length;i++)
objs[i] = new Object();
但是当我使用 for-each 循环时。
循环后数组元素仍然是null
:
Object[] objs = new Object[10];
for (Object obj : objs)
obj = new Object();
我认为 obj
指的是数组中的特定元素,
所以如果我初始化它,数组元素也将被初始化。
为什么没有发生这种情况?
最佳答案
I thought obj refers to a particular element in an array, so if I initialize it, the array element will be initialized as well. Why isn't that happening?
不,obj
在循环体的开始处具有数组元素的值。它不是数组元素变量的别名。所以像这样的循环(对于数组;对于可迭代对象是不同的):
for (Object obj : objs) {
// Code using obj here
}
相当于:
for (int i = 0; i < objs.length; i++) {
Object obj = objs[i];
// Code using obj here
}
参见 section 14.14.2 of the JLS有关增强型 for 循环的确切行为的更多详细信息。
关于java - 为什么不在增强的 for 循环中初始化数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19463935/