Java Reference
In-Depth Information
Question 9
Instead of calling the method
getReferenceTo
, could the method
remove
have
called the original definition of
contains
, as given in Segment 3.17? Explain.
Question 10
Revise the definition of the method
contains
so that it calls the private
method
getReferenceTo
.
Question 11
Revise the definition of the method
getReferenceTo
so that it controls its
loop by using a counter and
numberOfEntries
instead of
currentNode
.
Question 12
What is an advantage of the definition of
getReferenceTo
, as given in the
previous segment, over the one that the previous question describes?
3.24
The method
clear
.
In the class
ArrayBag
, as given in the previous chapter, the method
clear
called the methods
remove
and
isEmpty
to remove all entries from the bag. Since this definition
does not depend on how we represent the bag, we can use the same definition here in
LinkedBag
.
Thus,
clear
's definition is
public void
clear()
{
while
(!isEmpty())
remove();
}
// end clear
Note:
Deallocating memory
After the method
remove
removes a node from a chain, you have no way to reference the
removed node, so you cannot use it. As Segment B.20 in Appendix B noted, the Java run-
time environment automatically deallocates and recycles the memory associated with such
nodes. No explicit instruction from the programmer is necessary or, in fact, possible to cause
deallocation to occur.
Because
Node
is an inner class of the class
LinkedBag
,
LinkedBag
can access
Node
's private data
fields directly by name. Doing so makes the implementation somewhat easier to write, read, and
understand, particularly for novice Java programmers. However, some computer scientists feel that
you should access a class's data fields only by calling accessor and mutator (set and get) methods.
This section adds these methods to
Node
and explores three ways define this class.
3.25
As an inner class.
Suppose that we add the methods
getData
,
setData
,
getNextNode
, and
setNextNode
to the inner class
Node
, as it appears in Listing 3-1. The class would then appear as
given in Listing 3-4.
LISTING 3-4
The inner class
Node
with set and get methods
private class
Node
{
private
T data;
// entry in bag
private
Node next;
// link to next node
private
Node(T dataPortion)
{