patternjavaMinor
Linked List in Java (Garbage Collection)
Viewed 0 times
collectionjavagarbagelistlinked
Problem
So I'm implementing a linked list in Java, and so far it looks like this:
The line that I marked
public class List {
private class Node {
T value;
Node next;
}
private Node node_at(int n) {
Node seeker = front;
for (int i = 0; i l) {
node_at(length-1).next = l.front; // specific area of interest
length += l.length;
}
public T at(int n) {
Node seeker = node_at(n);
return seeker.value;
}
List() {
length = 0;
front = new Node();
}
}The line that I marked
specific area of interest is effectively cutting off a node (the last node in the receiver), leaving it homeless. Is that node going to get garbage collected?Solution
Yes, in theory. That depends on when the garbage collector decides to run. (There are lots of great explanations about how finicky it is on Stack Overflow.) But it will become eligible for garbage collection and is gone for all intents and purposes. Data becomes eligible for garbage collection when no references to it exist, and, assuming
node_at(length-1).next is the only reference to it, the Node then qualifies once you change that reference.Context
StackExchange Code Review Q#31868, answer score: 2
Revisions (0)
No revisions yet.