• Post Reply Bookmark Topic Watch Topic
  • New Topic

creating an array of objects using the new operator  RSS feed

 
Momen Travolta
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When an array of objects is created using the new operator, each element is a reference variable with a default value of null.


Shouldn't each element have a reference variable with a value of one object`s reference?

for example:-
myObject[] objArray = new myObject[10];

would assign the first element a reference to an instance of myObject; isn`t that right?
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. As you quoted, initially each element is null. You need to give each element a value:
 
kv ruby
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

myObject[] objArray = new myObject[10]; //alocates memory for 10 objects of type myObject.


this would create 10 reference variables of type myObject but the value assigned to each will be null.
hence these variables will hold the reference to objects only if we create Objects.

like objArray[0] = new myObject(); //first object is created and the rf of this object is stored in variable objArray[0].


 
Jonas Isberg
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ruby kv wrote:myObject[] objArray = new myObject[10]; //alocates memory for 10 objects of type myObject.

No need to allocate any memory for the actual myObjects here, only for the 10 reference variables.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arrays are like rolodexes. They hold address cards, not actual houses.

When you say

myObject[] objArray = new myObject[10];

you get a rolodex that has ten blank address cards in it. You need to build the house first (probably using the 'new' operator), then write the address on the card (using the assignment operator).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!