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 ?
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...
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();
You can create an object without new through: Reflection/newInstance, clone() and (de)serialization.
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());
}
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]);
}
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