Add objects with a different name through the 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 I do not want to create objects with the same name, I want to create them with a different name, for example o1,o2,o3,o4,o5,o6,o7,o8,o9,o10, and I want to add them to the list. What is the best way to do this?

+5
source share
7 answers

You do not need to use a different name for each object. Since the o1 object is declared in a for loop, the scope of the o1 variable is limited to the for loop, and it is recreated during each iteration ... except that each time it will refer to a new object created during this iteration. Please note that the variable itself is not saved in the list, but only the object to which it refers.

, , :

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

? for, , noe, .

: , , , , , - MyObjects :

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]);
}
+6

, . ,

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

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

( ),

Map<String, MyObject> map = new HashMap<String, MyObject>();

for (int i = 0; i < 10; i++) {
    map.put("o" + i, new MyObject());
}
+2
source

Your objects have no names. A variable o1has a name but is not associated with an object, except that the variable refers to the object. The object in the list does not know has ever referenced a variable o1.

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

for (int i=0; i<30;i++)
{
    list.add(new MyObject());
}
+1
source
doing it this way:

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

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

when i try to read the objects from the list they all return the same object with same values for instance variables.

i have an Emp class with 3 instance variables
name,dob and salary these values are read from list lst1.

for(int k=0;k<lst1.size();k++){ 

obj1=new Emp((lst1.get(k).get("name")),(lst1.get(k).get("dob")),

(lst1.get(k).get("salary")));

        lst3.add(k,obj1);
           }

but on reading lst3.get(3) or lst3.get(0)

Emp temp=lst3.get(3);

String name=temp.name;

come same as

Emp temp=lst3.get(0); 

String name=temp.name;

please provide me with a solution
+1
source

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

-1
source

All Articles