Java Reference
In-Depth Information
In some programming languages you have to explicitly free up memory when you
are no longer using it. That is not the case in Java. In Java you can simply stop refer-
ring to a node when you no longer want to use it. For example, consider the follow-
ing three-element list that we have constructed:
data
3
next
data
7
next
data
12
next
/
list
How would you get rid of the first node? You can reassign the variable list to
point to the node that comes after it. In effect, you leapfrog over the node that stores
3 and instead have list point to the node that stores 7 by writing the following line
of code:
list = list.next;
Now the linked list contains the following:
data
3
next
data
7
next
data
12
next
/
list
Now the variable list is pointing at a two-element list because it points at the
node storing 7, which in turn points to the node that stores 12 . The node that stores 3
is no longer pointed to by any variable.
What happens to a node when no variable points to it? As we mentioned at the end
of the previous chapter, the Java runtime system periodically invokes the garbage col-
lector to look for objects like this node and to reclaim the space so that it can be used
again. Java programmers enjoy the convenience of relying on this process, which is
sometimes called automatic garbage collection.
A good analogy is to think of each node as a helium balloon and the arrows as the
strings that we use to hold onto the balloons. If you let go of a string, then the balloon
floats away. But the garbage collector will find all of those stray balloons and reclaim
the space.
As one final example, consider what happens if you were to reset the list vari-
able to null :
list = null;
Our linked list would look like this:
data
3
next
data
7
next
data
12
next
/
list
/
 
Search WWH ::




Custom Search