add objects with different name through for loop

前端 未结 6 965
北海茫月
北海茫月 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 16:43

    What you could do (though that wouldn't make much sense either), is to use a Map instead of a List

    Map<String, MyObject> map = new HashMap<String, MyObject>();
    
    for (int i = 0; i < 10; i++) {
        map.put("o" + i, new MyObject());
    }
    
    0 讨论(0)
  • 2020-12-10 16:50

    Create the object give it a name, add your constructors. then add the object name to the arraylist.

    0 讨论(0)
  • 2020-12-10 16:55

    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]);
    }
    
    0 讨论(0)
  • 2020-12-10 17:02

    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());
    }
    
    0 讨论(0)
  • 2020-12-10 17:03

    Within the context of your loop, you don't need to worry about coming up with a name for each new instance you create. It's enough to say

    List<MyObject> list = new LinkedList<MyObject>();
    
    for(int i=0; i<30;i++)
    {
    list.add(new MyObject());
    }
    
    0 讨论(0)
  • 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());
    }
    
    0 讨论(0)
提交回复
热议问题