4

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?

2
  • No you only have to worry about Object 1 getting trashed when there are no references left to the lst structure. The elem reference is "fresh" each time. Commented Mar 9, 2012 at 23:52
  • 1
    Your two lines inside the loop can also be written as lst.add(new Obj()); Commented Mar 9, 2012 at 23:53

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.