简体   繁体   中英

java new operator in Array

I find the new operator a bit confusing. My understanding now is that

new ClassName(...)

is to make an instance and call the Class' constructor. But what does new do when initiating an Array? For example, I feel the two new operators below are different, but can't explain clearly.

Employee[] staff = new Employee[3];
staff[0] = new Employee(...);

Are there any difference?

Thanks.

new Employee[3] creates an array that can hold references to 3 Employee instances. Each of them is initialized to null. staff[0] = new Employee(...); creates an Employee instance and assigns its reference to the first index of the array.

Employee[] staff = new Employee[3];

Is initializing your array of Employee s with 3 "places" which can hold references to your Employee objects.
That means it reserves 3 times the space needed for one object/instance of your Employee class (eg 10byte) in the RAM (=> 30 byte).
But your array is initalized with "null". While staff[0] = new Employee(...); is creating a reference to your newly created object of type Employee . 数组

When you call the class' constructor, an instance (object) of that class is created. The "new" keyword is what tells the compiler to create an object. An array is a class and you make objects of type Array of SomeClass. You need to use the keyword "new" because you are still creating an object.

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