对于每个循环无法初始化数组中的对象 [英] for each loop cannot initialize objects in array

查看:81
本文介绍了对于每个循环无法初始化数组中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将迅速解决这个问题.我有一堂简单的课

I will dive quick to the problem. I have a straightforward class

class Vector{
    float x, y;
}

另一个类将这些对象的数组作为其成员

and another class has an array of these objects as its member

Vector[] buffer;

我这样初始化它:

buffer = new Vector[8];
for(Vector v: buffer)
    v = new Vector();

但是当我尝试访问此数组中该对象的成员时,我得到一个NullPointerException直接指向我的堆栈跟踪.也就是说,尚未构造数组的对象.另一方面,这种更为传统的代码非常完美:

but when I try to access this objects' members in this array I get a NullPointerException straight to my stack trace. That is, objects of array have not been constructed. On the other hand this more traditional code works just perfect:

buffer = new Vector[8];
for(int i = 0; i<8; i++)
    buffer[i] = new Vector;

正如讨论所指出的,两者都应编译后保持不变.

As this discussion points it out, both should be the same after compilation.

我的问题是,为什么每个循环都无法从item数组初始化/构造对象?

My question is, why for each loop fails to initialize/construct objects from the item array?

推荐答案

在每个示例中,您将覆盖循环的局部变量,该局部变量不会保存回数组中.这类似于您的第二个循环:

In your for-each example you are overwriting the local variable of the loop which does not get saved back into the array. It is similar to in your second loop going:

for(int i = 0; i < buffer.length; i++){
    Vector v = buffer[i];
    v = new Vector();
}

查看了解Java中的每个循环,了解基本相同的问题

Check out Understanding for each loop in Java for basically the same issue.

这篇关于对于每个循环无法初始化数组中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆