Java Reference
In-Depth Information
Node currentNode = firstNode;
while
((index < numberOfEntries) && (currentNode !=
null
))
{
result[index] = currentNode.data;
index++;
currentNode = currentNode.next;
}
// end while
return
result;
}
// end toArray
Programming Tip
If
ref
is a reference to a node in a chain, be sure that
ref
is not
null
before you use it to access
ref.data
or
ref.next
. Otherwise, if
ref
is
null
, a
NullPointerException
will occur.
Question 4
In the previous definition of
toArray
, the
while
statement uses the boolean
expression
(index < numberOfEntries) && (currentNode != null)
to control the loop. Is it
necessary to test the values of both
index
and
currentNode
? Explain your answer.
Earlier, we realized that the
add
method is fundamental to our class, so it is one of the core methods
that we implement and test first. The method
toArray
lets us see whether
add
works correctly, so it
too is in our core group. But what about the methods that are not in our core group? Because
LinkedBag
implements the interface
BagInterface
, it must define every method in the interface.
As the previous chapter described, we write stubs for methods that are declared in the interface but
are not a part of our core group. Since the methods
getCurrentSize
,
isFull
, and
isEmpty
have
simple definitions, we will write them instead of stubs in this first draft of the class
LinkedBag
.
Note:
The method
isFull
should always return false. As noted in Segment 3.13, the only
time a bag whose implementation is linked could appear full is when the system cannot pro-
vide memory to the
add
method for a new node. In that case, an
OutOfMemoryError
occurs,
which is fatal. A client would not have the opportunity to call
isFull
.
A test program for
LinkedBag
1
could be just like the one for
ArrayBag
, as given in Listing 2-2
of the previous chapter, except for its name, the class used to create a bag, and one other significant
distinction: Although an instance of
ArrayBag
can become full, an instance of
LinkedBag
will not.
Listing 3-3 outlines such a test program. Notice that the private static methods here are exactly the
same as those given in Listing 2-2 of the previous chapter. This is possible because the methods use
BagInterface
as the data type of a bag.
1.
Note that this version of the class
LinkedBag
is available online at the topic's website and is named
LinkedBag1
.