views:

337

answers:

4

If I have a linked list structure, and I implement the clear() method as follows:

public void clear() {
    firstNode = null;
    size = 0;
}

will it still get correctly garbage collected, or would I want to walk through each node, setting nextNode to null?

None of the nodes can be directly referenced from outside the linked list, so there's no case where there would be a reference to any of them outside my class, but I'm unsure if Java would correctly garbage collect the remaining chained nodes.

A: 

Java does , automatic garbage collection .

pavun_cool
+8  A: 

That should be fine - Java handles cyclic references etc with no problems.

Jon Skeet
+1  A: 

for your information, the LinkedList implementation by Sun parse all elements of the list and set them to null

chburd
True, but this is only necessary because Java's LinkedList is doubly linked
Michael Borgwardt
+1  A: 

Since none of the nodes of the list have external references. Setting firstNode to null will make all the nodes eligible for GC as there would be no way to reach any of the nodes from an external reference.

codaddict
+1 for clarifying that GC doesn't count references, it determines reachability.
Andy Thomas-Cramer