0
votes
  1. When is a node in a singly linked list eligible for garbage collection?
  2. If there is a node in a singly linked list which is the last element then its next pointer will be pointing to null. If suppose the data in this last element is also null. In that case both the data and next pointer are null. Will this element be eligible for garbage collection?
2

2 Answers

0
votes

An object is garbage collectible if and only if there are no references to it.

What this means is, the object will not become a candidate for gc until all references to it are discarded.

If there is a node in a singly linked list which is the last element then its next pointer will be pointing to null. If suppose the data in this last element is also null. In that case both the data and next pointer are null. Will this element be eligible for garbage collection?

Still no!! The last node is accessible from the 2nd last element. Java will not clean the last element. It has nothing to do with contents of an object being null.

0
votes

No Node is not eligible for garbage collection because this node still access from 2nd last node.

This node is eligible for garbage collection only 2nd last node next pointer is NULL.

Example: there is linked list which have 5 node. 1->2->3->4->5->null;

Case:1 Node 5 next field contain NULL. if node 5 value also contain NULL, but node 4 next field still point to node 5 so node 5 not eligible for garbage collection .