开发者

Delete/free a linked list node in Java. Suggestion please

All, If I were to write a function to delete a node (given headNode and data as input parameters) from a linkedList in Java. I would find the node that has "node.data=data", and delete开发者_如何学Go it by pointing its previous node to its next node *^. My question is, do we have to point the "to be deleted" node to null? to free the memory? or the GC will take care of objects no more accessed in heap.

*^: say A->B->C->D , if B.data=data, then make A->C . is B->Null necessary?

please let me know if its not clear, I will edit it. Thanks.


If you want to delete Node B you just need for A to point to C. The garbage collector will take care of your B nodes as there won't be any references left to it.

The following explanation is quoted from http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.html

An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static refrences in other words you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as reference so if Object A has reference of object B and object B has reference of Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection.

Generally an object becomes eligible for garbage collection in Java on following cases:

1) All references of that object explicitly set to null e.g. object = null

2) Object is created inside a block and reference goes out scope once control exit that block.

3) Parent object set to null, if an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.

4) If an object has only live references via WeakHashMap it will be eligible for garbage collection.


As everyone has said you don't need to set it to null. I just want to add that I had a similar question before which might not be obvious. If you have a doubly linked list, where each node references the previous and the next node, for example A-B-C-D and you remove C-D so that you're left with A-B. You also do not need to worry about C or D even though both of them still have a reference to them (from the other one). Apparently the GC is smart enough to take care of that case as well


No you don't have to set B to null. The Java garbage collector will free the memory for any object not reachable anymore.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜