java - 为什么不在增强的 for 循环中初始化数组元素?

标签 java arrays for-loop

当我使用普通的 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/

相关文章:

Scala遍历列表,除了最后一个元素

c++ - 在for循环中找到最小值并保留它的索引

java - 如何将时间 "0000-00-00 00:00:00"设置为 LocalDateTime?

令人头疼的 Javascript 数组排序

java - ActionListener 和 ActionEvent 位于不同的类中

c++ - 使用数组减去数字 - C++

javascript - 如何使用纯 JavaScript 访问最内层的双重嵌套数组/对象?

JavaScript 循环和数组

java - 在 hibernate 中处理一对多关系

java - 围绕它的中心旋转一个矩形多边形。 ( java )