Ben Marshall
Ben Marshall

Reputation: 171

Setting objects in an ArrayList to null

If I was to have an ArrayList of objects, and I set a few of them to null, are they susceptible to gc? Or will they stay since they are still being referenced by the ArrayList

ex:

for(NPC n : NPCs){
    n.act();
    n.draw(frame);
    if(n == outOfMap){
            n = null;
        }

}

If that loop is "always" being iterated over, will the outOfMap objects be collected? or simply stay there will a null value?

Upvotes: 2

Views: 5128

Answers (2)

Ameen
Ameen

Reputation: 2586

You need to distinguish between objects and references to them. For the same one object, multiple references could point to it. When the number of references reaches 0, the object is a candidate to be removed by the garbage collector.

In this loop:

for(NFC n : NFCs)
{
   n = null;
}

The n reference is different than the reference the ArrayList uses to track the object in the list, so setting n to null reduces the references to the object down by one, but it leaves the reference from the ArrayList to the object intact and as such, the object is not a candidate for garbage collection. You should use the remove method to remove the object from the ArrayList. At that point, if no other references to the object exist elsewhere, it'll be a candidate for removal.

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You're confused I think between variables and objects. If a variable references null, there's nothing to GC since variables aren't GC'd, objects are. The ArrayList won't be GC'd if there's a valid reference to it, and if it contains nulls, then there's nothing in it to be held in memory or to GC.

If on the other hand, the ArrayList contains objects, and then later you null an item or two, then it's not the ArrayList that will determine the GC-ability of the object since its reference to it has been severed, but whether or not other objects reference them.

Upvotes: 0

Related Questions