add objects with different name through for loop

前端 未结 6 990
北海茫月
北海茫月 2020-12-10 16:18

What is the best way to do the following:

List list = new LinkedList();

for(int i=0; i<30;i++)
{
  MyObject o1 = new MyOb         


        
6条回答
  •  臣服心动
    2020-12-10 17:03

    Your objects don't have names. The variable o1 has a name, but it's not linked to the object except that the variable refers to the object. The object in the list has no knowledge of ever having been referenced by the variable o1.

    For what you're doing, you don't need a variable at all, as Stephen said in his answer you can just add the objects directly:

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

提交回复
热议问题