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.
Answer: Yes. Java can have an array of objects just like how it can have an array of primitive types. Q #2) What is an Array of Objects in Java? Answer: In Java, an array is a dynamically created object that can have elements that are primitive data types or objects.
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;
}
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