Reputation: 1200
I have a Singly Linked List
a->b->c->d->e
a,b,c,d and e are objects of type node. I want to delete a node while traversing through the list and subsequently make the deleted node the head of the list as shown in the code below
list.delete(iterator, current);
list.addObjectAtFront(current);
public void delete(ListIterator li, Node node) {
if (li == null) {
throw new NullPointerException();
}
li.next();
if (li.previous() != null) {
li.previous().setNext(node.getNext());
}
}
public void addObjectAtFront(Object o) {
Node newNode = new Node(null, o);
if (this.head != null) {
newNode.setNext(this.head);
this.head = newNode;
} else {
this.head = this.tail = newNode;
}
}
Say the current item is c when the above methods are called. I expect the following
list.delete(iterator, current);
Output: a->b->d->e
list.addObjectAtFront(current);
Output: c->a->b->d->e
I have 2 conflicting thoughts
After being deleted, c isnt pointing to any other node and can be garbage collected before the second method is called.
c cant be garbage collected since it isnt itself null and has some data in it. This will mean that if i didnt ever need to make use of c; it will just keep hanging around in memory.
Which of this is correct or have I got it wrong completely and need a fresh understanding of object references?
Upvotes: 3
Views: 73
Reputation: 7796
Garbage collection will never delete memory that you have any way of referencing(Unless you use a WeakReference)
That is, if you still have a use for the node, be assured that java will not garbage collect it away from you. As a programmer you do not need to think about how the garbage collector behaves, unless it's for performance enhancements. GC should never effect the correctness of code.
Which of this is correct or have I got it wrong completely and need a fresh understanding of object references?
To answer directly, neither. When you delete, you use a reference to the node called current
. This reference IS the SAME reference as c. When c gets removed, you still have current which is referencing it. Then you add current to the front of the list. Now you have 2 references to it again, then you lose the current reference when it drops from scope, bringing you back down to 1 reference.
c never gets garbage collected.
Upvotes: 3
Reputation: 30032
Just because an object has data in it doesn't mean it won't be garbage collected. The garbage collection checks to see if you are holding any references to it. If your only reference to c
was in your linked list and you remove it, then it will be garbage collected.
Upvotes: 2
Reputation: 1599
c wont be garbage collected since 'current' is referencing it.
One object can be garbage collected when there are no live references to it, but remember one object can have more than one references to it.
Upvotes: 1