Tuesday 7 May 2019

Creating an array of objects in Java



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



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 as




a1 = new A();


similarly, with the array you need to do



a[0] = new A();


before using it.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...