Creating an array of objects in Java

user220201 picture user220201 · Mar 19, 2011 · Viewed 778.7k times · Source

I am new to Java and for the time created an array of objects in Java.

I have a class A for example -

A[] arr = new 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.

EDIT: I find this odd because in C++ you just say new A[4] and it creates the four objects.

Answer

MeBigFatGuy picture MeBigFatGuy · Mar 19, 2011

This is correct.

A[] a = new A[4];

...creates 4 A references, similar to doing this:

A a1;
A a2;
A a3;
A a4;

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();

...before using it.