在 Java 中创建对象数组 [英] Creating an array of objects in Java
问题描述
我是 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++ 中你只需说 new 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
的情况下做 a1.someMethod()
像这样:
Now you couldn't do a1.someMethod()
without allocating a1
like this:
a1 = new A();
同样,对于数组,您需要这样做:
Similarly, with the array you need to do this:
a[0] = new A();
...在使用之前.
这篇关于在 Java 中创建对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!