Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: efficient way of memory allocation for an array of objects

Tags:

java

In the code below I am trying to avoid the last three lines which allocate memory for the instances of class. Any suggestions on how to bring the memory allocation part inside the class definition? So what I want to do is to be able to execute pInfo[0].sValue="string"; right after AClass [] pInfo = new AClass[10];

  class AClass {
     private String sName="";
     private String sValue="";
  }

    AClass [] pInfo = new AClass[10];

   // how to avoid the code below or bring them into class definition?  

    pInfo[0] = new AClass();
    pInfo[1] = new AClass();
      ... 
    pInfo[9] = new AClass();

EDIT: what I mean by efficiency is in the amount of code + code readability

like image 329
C graphics Avatar asked Jan 15 '23 22:01

C graphics


2 Answers

AClass[] pInfo = {new AClass(),new AClass(), etc.};

OR

AClass[] pInfo = new AClass[10];

for(int i = 0; i < pInfo.length; i++)  
{  
    pInfo[i] = new AClass();  
}  
like image 81
Woot4Moo Avatar answered Jan 18 '23 23:01

Woot4Moo


There is no way to avoid that, you will need to explicitly assign a value to each element of your array.

JLS §10.3 states that arrays provide initial values for their elements when they are created.

JLS §4.12.5 states that the initial value for reference types is null.

like image 45
Jeffrey Avatar answered Jan 19 '23 01:01

Jeffrey