Creating a list of objects in Java

So, I was thinking of creating a list of objects like this

ArrayList<Obj> lst = new ArrayList<Obj>(10); for (int i = 0; i < 10; i++) { Obj elem = new Obj(); lst.add(elem); } 

Is this legal, or do I need to worry about object 1 getting garbage when the elem link starts pointing to Object 2? If it is illegal, how can I do it otherwise? Is there a way to automatically generate ten different link names?

+4
source share
3 answers

The garbage collector will remove objects only when there are no links pointing to it. In your case, your list will point to 10 different Object objects, and they are safe until you lose the link to the lst Object.

+5
source

This is completely legal. Your ArrayList will contain a reference to the object you just created, so it will not be GCed.

+3
source

Your approach is absolutely correct. You will get a list of ten different objects.

+1
source

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


All Articles