Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

java - add objects with different name through for loop

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...