Reputation: 55
I may be wrong but from what I understand when creating an object in java by:
Class object = new Class;
the new Class
create new object of Class type which is then applied to "object"
reference
so when u create array of objects by:
Class[] objects = new Class[10];
does it mean new Class[10]
creates 10 objects of Class type wich are then applied to objects
reference or just a memory for size of 10 objects of Class type is reserved and you need to create certain objects later
Upvotes: 3
Views: 357
Reputation: 2692
Creating an array of objects is similar to create variables i.e. the code
Class[] objects = new Class[10];
can be interpreted as
Class object1;
Class object2;
...
for using them or calling function and accessing variables we have to call the constructor ie.
object1 = new Class();
object2 = new Class();
So Class[] objects = new Class[10];
is creating 10 references of Class and no memory allocation has been done for the objects. For doing that we have to call the constructor for them like object[0] = new Class();
Now the objects have been created memory has been allocated and we can use them.
Also if after creation of array of objects without calling constructor we use them like object[0].somefunction() it will show null pointer exception.
Upvotes: 0
Reputation: 2166
objects will be a pointer to an array of pointers. These pointers will point to objects of type Class. No memory is allocated for anybody but the actual pointers. So new Class[10] creates 10 pointers, which are referenced by objects.
Upvotes: 0
Reputation: 191
Consider the following example: bool [] booleanArray; FileInfo [] files;
booleanArray = new bool[10];
files = new FileInfo[10];
Here, the booleanArray is an array of the value type System.Boolean, while the files array is an array of a reference type, System.IO.FileInfo. The following figure shows a depiction of the CLR-managed heap after these four lines of code have executed.
Eventhough this is a C# example. This is similar to what we have in Java.
Upvotes: 0
Reputation: 41097
new Class[10]
does create memory for 10 placeholders. It does not allocate the memory for individual entries.
Upvotes: 0
Reputation: 9946
Later is correct new Class[10]
will create a placeholder for 10 objects in memory and you need to put objects explicitly in them.
Upvotes: 1