qqq
qqq

Reputation: 936

Java - Can we set firstNode to null in a linked node to remove all entries?

I have the below code:

public final class LinkedBag<T> implements BagInterface<T> {
    private Node firstNode;
    private int numberOfEntries;

    public LinkedBag() {
        firstNode = null;
        numberOfEntries = 0;
    }

    // Other methods defined
    public int getCurrentSize() { }
    public boolean isEmpty() { }
    public boolean add(T newEntry) { }
    public T remove() { }
    public boolean remove(T anEntry) { }
    public int getFrequencyOf(T anEntry) { } 
    public boolean contains(T anEntry) { }
    public T[] toArray() { }

    public void clear() { 
        while(!isEmpty())
            remove();
    } 
}

To remove all entries the above version of the clear() method deallocates each node in the chain, thereby making it empty.

However, to remove all entries would the below version of the clear() method deallocate all of the nodes in the chain, thereby making it empty?

    public void clear() { 
        firstNode = null;
    }

Upvotes: 1

Views: 899

Answers (3)

Shubham Srivastava
Shubham Srivastava

Reputation: 95

Yes making the first node null will work. As reference to all subsequent nodes will be lost and they will be deallocated automatically by a garbage collector.

Upvotes: 1

kaya3
kaya3

Reputation: 51112

Yes; except you should also remember to set numberOfEntries = 0; too. Then your linked list is in the same state as if a new empty linked list was just created (note that your constructor does the same two things), so it correctly represents an empty list.

Regarding the garbage collector, this will deallocate the removed node objects behind the scenes, automatically, because they are no longer reachable by live references. To avoid memory leaks in garbage-collected languages like Java, the main issue is making sure you don't retain references to data you no longer need. In this case, after setting firstNode = null; your instance retains no references at all, so there is no memory leak.

Upvotes: 1

Thiyagu
Thiyagu

Reputation: 17910

Yes, it would. Unlike C/C++ where we have the take care of deallocating the memory we have allocated earlier, Java takes care of collecting the garbage when there are no strong references to an object.

When you make the head of the linked list (firstNode) to null, there wouldn't be (and shouldn't be) any references to that node. Hence, it is eligible for garbage collection (GC). Looking at the second node in the list, there would no other links to it other than the head and hence it is also eligible to be collected.

Extending this, the entire list (all the nodes in the list) can be GCed.

Upvotes: 1

Related Questions