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
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();
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With