6

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.

1
  • 1
    Don't think of it as "memory creation" (in fact, the memory was already created in some asian factory, and now resides in your computer, in the form of a chip). Think of it as class instance creation. Commented Dec 5, 2013 at 14:38

2 Answers 2

25

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

I found below really helpful when creating array of custom objects in single line:

public class Hotel {
    private int frequency;
    private String name;
    public Hotel(int frequency,String name){
        this.frequency = frequency;
        this.name = name;
    }
}
public class PriorityQueueTester {
    public static void main(String args[]){
        Queue<Hotel> hotelPQ = new PriorityQueue<Hotel>();
        Hotel h[] = new Hotel[]{new Hotel(4,"Harshil"),new Hotel(5,"Devarshi"),new Hotel(6,"Mansi")};
        System.out.println(h[0].getName() + " "+h[1].getName()+" "+h[2].getName());
    } 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.