Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list of objects in Java

Tags:

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 have to worry about Object 1 getting trashed when the elem reference starts pointing to Object 2? If it's illegal, how might I do it otherwise? Is there a way to automatically generate ten different reference names?

like image 411
i love stackoverflow Avatar asked Jan 17 '23 06:01

i love stackoverflow


1 Answers

Garbage Collector will remove objects only when there are no references pointing to it. In your case, your list will be pointing to 10 distinct Object objects and they are safe until you lose reference to lst Object.

like image 59
Magesh khanna Avatar answered Jan 19 '23 21:01

Magesh khanna