问题描述
我是Java的新手,在Java中创建了一个对象数组。
I am new to Java and for the time created an array of objects in Java.
我有一个A类例如 -
I have a class A for example -
A[] arr = new A[4];
但这只是创建指向A而不是4个对象的指针。它是否正确?我看到,当我尝试访问函数/变量在对象创建我得到一个空指针异常。
为了能够操作/访问对象,我必须这样做 -
But this is only creating pointers (references) to A and not 4 objects. Is this correct? I see that when I try to access functions/variables in the objects created I get a null pointer exception.To be able to manipulate/access the objects I had to do this --
A[] arr = new A[4];
for( int i=0; i<4; i++ )
arr[i] = new A();
这是正确的,还是我做错了?如果这是正确的它真的奇怪。
Is this correct or am I doing something wrong? If this is correct its really odd.
编辑:我发现这是奇怪的,因为在C + +你只是说新的A [4],它创建了四个对象。 >
I find this odd because in C++ you just say new A[4] and it creates the four objects.
推荐答案
这是正确的。
A[] a = new A[4];
创建4个A引用,与执行此操作类似
creates 4 A references, similar to doing this
A a1;
A a2;
A a3;
A a4;
现在你不能做a1.someMethod
$ b
now you couldn't do a1.someMethod() without allocating a1 as
a1 = new A();
同样,你需要做的数组
a[0] = new A();
。
这篇关于在Java中创建对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!