Creating array of custom objects in java

arrays, java

Solution

When you do this:

Object[] myArray = new Object[100]

Java allocates 100 places to put your objects in. It does NOT instantiate your objects for you.

You can do this:

SomeClass[] array = new SomeClass[100];

for (int i = 0; i < 100; i++) {
    SomeClass someObject = new SomeClass();
    // set properties
    array[i] = someObject;
}

Problem

I have a 100 records of data which is coming to my system from a service. I want to create 100 Class Objects for each record for serializing it to my Custom Class. I was doing this memory creation inside a for loop as follows ``` for(int i=0; i < 100; i++) { SomeClass s1 = new SomeClass(); //here i assign data to s1 that i received from service } ``` Is there any way to create all the 100 objects outside the array and just assign data inside the for loop. ``` I already tried Array.newInstance and SomeClass[] s1 = new SomeClass[100] ``` Both result in array of null pointers. Is there any way i can allocate all the memory outside the for loop.

Original source