Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add objects with different name through for loop

Tags:

java

What is the best way to do the following:

List<MyObject> list = new LinkedList<MyObject>();

for(int i=0; i<30;i++)
{
  MyObject o1 = new MyObject();
  list.add(o1);
}

But the things is I don't wanna create objects with same name, I wanna create them with different name like o1,o2,o3,o4,o5,o6,o7,o8,o9,o10 and I wanna add each to the list. What is the best way to do this ?

like image 828
Gandalf StormCrow Avatar asked Mar 12 '10 13:03

Gandalf StormCrow


People also ask

Can I create objects in a loop Java?

You CAN use a loop. The trick is that you have to save the reference to each one as you create it. A simple way would be to use an array. You have to declare the array outside the loop, then use your loop counter as the index into the array...

How do you create multiple objects in Java?

Your problem is that you are trying to do two things in the same go : create an array and assign value to specific element of it. This is how you should operate an array: int length = 5; // predetermined by you constant User []users = new User[length]; //.... users[i] = new User();

Can we create object without using new keyword in Java?

You can create an object without new through: Reflection/newInstance, clone() and (de)serialization.


2 Answers

You don't need to use a different name for each object. Since the o1 object is declared within the for loop, the scope of the o1 variable is limited to the for loop and it is recreated during each iteration ... except each time it will refer to the new object created during that iteration. Note that the variable itself is not stored within the list, only the object that it is referring to.

If you don't need to do anything else with the new object other than add it to the list, you can do:

for(int i=0; i<30;i++)
{
  list.add(new MyObject());
}
like image 115
Stephen Doyle Avatar answered Oct 05 '22 21:10

Stephen Doyle


Why would you like to give them different names? You're creating the object inside the for loop, so it doesn't exist outside, and I therefor see noe reason to give them different names.

To answer your question: The only way I see, but I might be wrong, is to make an array of MyObjects and do:

List<MyObject> list = new LinkedList<MyObject>();
MyObject[] o = new MyObject[30];

for(int i = 0; i < 30; i++) {
    o[i] = new MyObject();
    list.add(o[i]);
}
like image 41
martiert Avatar answered Oct 05 '22 19:10

martiert