How jvm handles object creation inside a loop

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 does the JVM handle creating an a object in each loop? How does a “list” differ between different instances? Good practice is to create an object at each iteration. If not, then the best solution is to add an object to the list.

0
source share
4 answers

In your example, a new object is created at each iteration of the loop. The list can distinguish between each other, because it doesn’t matter what you call them "a" in your code, it tracks them by a link that is reassigned every time you call

 a = new A(); 

Each time this line of code is called, a new object is created on the heap, and this address in memory is assigned to the link a. This is the link that the record is stored in the list, not the variable name.

This is a great and normal way to populate the list (in addition to the syntax errors that others have mentioned, which I assume you can fix when you try to compile your code).

+6
source

The list contains a link to each instance of the created object. This is great to create every object inside a loop (I assume you mean, by contrast, declaring the variable "a" outside the loop, and then reassigning each iteration).

+2
source

Is it good to create a new object at each iteration? One of my friends told me that it is not a good practice to create such cases.

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

Regarding declaring the variable a outside the loop, I don’t think it makes a difference in performance, but also reduces readability.

 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); } 
+1
source

If my understanding of the JVM is correct, the published code will not have a 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 of creating a new instance with a specific name)

+1
source

Source: https://habr.com/ru/post/1493792/


All Articles