简体   繁体   中英

what exactly happens when new operator is called for array and object?

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

稍后是正确的new Class[10]将为内存中的10个对象创建占位符,您需要在其中显式放置对象。

new Class[10] does create memory for 10 placeholders. It does not allocate the memory for individual entries.

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.

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 .

Creating an array of objects is similar to create variables ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM