Linked List:
public class ListNode {
public int val;
public ListNode next;
public ListNode(int val=0, ListNode next=null) {
this.val = val;
this.next = next;
}
public static void Main(){
ListNode head = new ListNode(5);
ListNode curr = head;
curr.next = new ListNode(6);
curr = curr.next;
curr.next = new ListNode(7);
curr = curr.next;
curr.next = new ListNode(8);
curr = null;
}
I created a Linked using above code.
head is a ListNode identfier which points to node1 intially.
After pointing head to node2, will node1 be collected by garbage collector? Note that node1 is not referenced by any identifier now however it's next pointer in heap memory still points to a non-null object?
Edit: As per my understanding GC collects all the free objects that are not in use but here node1 is not completely free since its connected to the linked list which is still in use.