Reputation: 2757
this is a sample code from delete function in my LinkedList class which deletes a node from middle.
temp.getPrev().setNext(temp.getNext());
temp.getNext().setPrev(temp.getPrev());
temp.setNext(null);
temp.setPrev(null);
my question is do i have to set temps next and prev references to null or does garbage collector handle with this automatically_?. i will appreciated very much if you can help me. and thanks anyway.
Upvotes: 1
Views: 2620
Reputation: 86509
my question is do i have to set temps next and prev references to null or does garbage collector handle with this automatically_?
You do not have to set references in an object's fields to null before it becomes unreachable.
Nor will the garbage collector set them to null for you.
But a reference to an object from an unreachable object does not prevent garbage collection.
So if later on the only references to the next (or previous) node are from other unreachable nodes, then that node can be collected.
Upvotes: 0
Reputation: 875
The GC only takes references to an object in consideration. It does not matter if the object has references to other objects.
Upvotes: 1
Reputation: 9149
Garbage Collector analyze if there is any reference to an object. Since there is no reference to temp
after your method is finished, GC should remove this object.
Upvotes: 4
Reputation: 1135
You have to make sure that there are no live references to temp. You don't need to do anything extra.
Upvotes: 1
Reputation: 597382
I don't think you should. The node is no longer referenced anywhere, so even though it references valid objects, it will be garbage-collected.
Upvotes: 1
Reputation: 91983
The garbage collector will see when there's no references left to temp
. Therefore you don't have to care about nulling outgoing references - if you can't reach temp anymore it will be garbage collected (eventually).
Upvotes: 1