views:

492

answers:

4
List list = new ArrayList();


String[] test = {"ram", "mohan", "anil", "mukesh", "mittal"};

for(int i =0; i < test.length; i++)

{

  A a = new A();

  a.setName(test[i]);

  list.add(a);

}

How JVM handles creation of object a in each loop? How "list" differntiate between different instance? Is it good practice to create object on each iteration. If no, what is the best solution for adding object into a list.

+2  A: 

List holds a reference to each instance of a that gets created. It's fine to create each object inside the loop (I'm assuming you mean as opposed to declaring the 'a' variable outside the loop and then re-assigning it each iteration).

AgileJon
Yes. you are correct. One of my friends told me that it is not a good practice to creating so much instances. It can decrease the performance of application.
Shashi Bhushan
@Shashi Bhushan: Unless you need all of the instances, of course, in which case it makes sense to create them. :)
Eddie
@shashi however, creating multiple instances is perfectly okay.
Here Be Wolves
+6  A: 

In your example a new object is created on each iteration of the loop. The list is able to differentiate between them because it does not care that you call them all "a" in your code, it keeps track of them by the reference that gets reassigned each time you call

a = new A();

Each time that line of code is called, a new object is created on the heap and it's address in memory is assigned to the reference a. It's that reference that the list keeps a record of, not the variable name.

This is a perfectly fine and normal way to populate a list (aside from the syntax errors that others have mentioned, which I'm assuming you can fix when you try to compile your code).

Bill the Lizard
A: 

Is it good practice to create a new object on each iteration? One of my friends told me that it is not a good practice to creating so much instances.

If you need different individual instances, you need to create them. Since your list needs five objects with different names each (ram, mohan, anil and so on), you need a new object for every iteration of the loop. How else are you going to store the five names?

As for declaring the variable a outside of the loop, I do not think that makes a difference performance-wise and also reduces legibility.

A a;  // dont do this
for(int i =0; i < test.length; i++){
  a = new A();
  a.setName(test[i]);
  list.add(a);
}

You might be interested in the for-each loop

for(String name: test){
   A a = new A();
   a.setName(name);
   list.add(a); 
}
Thilo
A: 

If my understanding of the JVM is correct, the posted code will have no performance difference compared to

for (String name : test )
{
   list.add(new A(name));
}

(assuming, of course, that the constructor A(String s) is another way to create a new instance with a specific name)

Christoffer