i love stackoverflow
i love stackoverflow

Reputation: 1685

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 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?

Upvotes: 4

Views: 15478

Answers (3)

Magesh khanna
Magesh khanna

Reputation: 193

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.

Upvotes: 5

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103155

Your approach is perfectly valid. You will end up with a list of ten distinct objects.

Upvotes: 1

Jeffrey
Jeffrey

Reputation: 44808

It's perfectly legal. Your ArrayList will contain a reference to the object you just created, so it will not be GCed.

Upvotes: 3

Related Questions