Reputation: 59
How do I delete a linked list completely in java. Some tutorials are suggesting that I should delete it node by node . But if I make head to null simply, would it be wrong ? As all the elements would be eligible for garbage collection.
Upvotes: 0
Views: 1021
Reputation: 16664
Yes, you can simply assign the head
as null
but to be on the safe side (as in if some nodes are being referred from elsewhere) it is better to make all nodes null
.
If you look at the code in java.util.LinkedList
, the clear() method does the same.
/**
* Removes all of the elements from this list.
* The list will be empty after this call returns.
*/
public void clear() {
// Clearing all of the links between nodes is "unnecessary", but:
// - helps a generational GC if the discarded nodes inhabit
// more than one generation
// - is sure to free memory even if there is a reachable Iterator
for (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++;
}
first
reference is head
in your case.
You can also refer to this comprehensive answer.
Upvotes: 0
Reputation: 2820
You can point the LinkedList
reference variable to null
.
Any reference variable referring to null
is automatically eligible for Garbage Collection
List list = new LinkedList();
list.add("hi");
list = null; // now eligible for *Garbage Collection*, leave it for JVM to handle
Moreover if you do list.clear()
it will clear all the elements inside this list
but not the list
itself.
Also we can call System.gc()
but System.gc()
will not ensure that Garbage Collector will run for sure, it can only asks the JVM to run the GC , but is totally dependent on JVM, so we should levae it to JVM only to handle GC.
For more info see this Oracle Doc here
Upvotes: 0
Reputation: 234635
You can't. You can only recommend the list as a candidate for garbage collection by removing all references to it.
If you own the only reference then setting that reference to null
will schedule the object for garbage collection. You can advise a garbage collection using System.gc()
but that's not particularly good style and not all JVMs support it.
Removing the elements node by node (use clear()
) can help a little since it will reduce the number of references held on each of the list items. That will reduce the amount of memory that the list consumes.
Upvotes: 2