Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating array of custom objects in java

Tags:

java

arrays

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.

like image 602
kishore Avatar asked Dec 05 '13 14:12

kishore


People also ask

Can you create an array of objects in Java?

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.


1 Answers

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;
}
like image 88
ioreskovic Avatar answered Oct 19 '22 07:10

ioreskovic