java - Deleting a single linked list by just making head = null? -
why can't make head=null
delete complete linked list?
3 = head > 1 > 2 > 4 > null
by making head = null
, jvm take care of it.as head node not referenced variable , should garbage collected.
what wrong solution?
note: i'm aware of correct solution delete complete link list i'm curious why can't make head=null
delete complete linked list?
here's code of java.util.linkedlist.clear(), verbatim:
public void clear() { // clearing of links between nodes "unnecessary", but: // - helps generational gc if discarded nodes inhabit // more 1 generation // - sure free memory if there reachable iterator (node<e> x = first; x != null; ) { node<e> next = x.next; x.item = null; x.next = null; x.prev = null; x = next; } first = last = null; size = 0; modcount++; }
the comment answers question. it's unnecessary. can gc, , can make more objects eligible gc sooner if there iterator references 1 of nodes: referenced node still won't eligible gc, nodes after , before referenced node be, since they're not referenced anymore.
note developer chose make clear() method slower (o(n) instead of o(1)), make gc faster , reduce "memory leaks". inverse choice.
also note might never call clear(), , stop referencing object of type linkedlist, leaving nodes linked together. gc collect nodes if none of them reachable through reference chain gc root. that's happens 99% of times use list.
Comments
Post a Comment