rk.the1
rk.the1

Reputation: 109

Will link list be deleted if head is set to null in java?

In java garbage collector takes care of cleaning the objects which don't have any reference. I was wondering if head of a singly linked list is set to null, there will be no reference to the next list node and so, garbage collector should mark it for cleaning and we need not traverse the full list and delete the nodes one by one ?

Upvotes: 1

Views: 991

Answers (2)

GhostCat
GhostCat

Reputation: 140613

Garbage collection checks for alive objects.

While some of your objects hold a reference to that list, the list (and all its members are alive).

If that reference to the list stops to exist; for example by setting it to null; your list object is no longer alive. So, it becomes subject to garbage collection.

For the objects within your list, the very same things apply. So - if that list was the only place that kept a reference to the element, then the element isn't alive any more after the list was "nullified". Then the list element can be collected, too. But if there is some other alive object that refers to the list element ... the list element stays; although the list itself is collected.

In other words: you should try to think like the garbage collector: understand which objects are alive; and anything else stops being important.

Upvotes: 1

Richard Schwartz
Richard Schwartz

Reputation: 14628

Yes. In fact, even if the list is circular, it will be garbage-collected as long as there are no live references to any list element from anywhere outside of the list. See here for more info about that.

Upvotes: 0

Related Questions