Java Reference
In-Depth Information
LISTING 3-3
A sample program that tests some methods in the class
LinkedBag
/** A test of the methods add, toArray, isFull, isEmpty, and
getCurrentSize, as defined in the first draft of the class LinkedBag.
@author Frank M. Carrano
*/
public class
LinkedBagDemo1
{
public static void
main(String[] args)
{
System.out.println("Creating an empty bag.");
BagInterface<String> aBag =
new
LinkedBag<String>();
testIsEmpty(aBag,
true
);
displayBag(aBag);
String[] contentsOfBag = {"A", "D", "B", "A", "C", "A", "D"};
testAdd(aBag, contentsOfBag);
testIsEmpty(aBag,
false
);
testIsFull(aBag,
false
);
}
// end main
< The static methods
testAdd
,
testIsFull
, and
displayBag
from Listing 2-2 are here. >
< The static method
testIsEmpty
is analogous to
testIsFull
and is here. >
}
// end LinkedBagDemo1
3.16
To count the number of times a given entry appears in a bag, we must traverse the chain of nodes and
look at the entry in each one. The traversal is much like the one we used in the method
toArray
. Thus,
if
currentNode
will reference the node that we want to examine, we set it initially to
firstNode
—the
first node in the chain—and then use the statement
currentNode = currentNode.next;
to advance it to the next node. Using this technique, we can write a loop like the following one:
int
counter = 0;
Node currentNode = firstNode;
while
((counter < numberOfEntries) && (currentNode !=
null
))
{
VideoNote
Completing the class
LinkedBag
. . .
counter++;
currentNode = currentNode.next;
}
// end while
Although the method
toArray
uses the variable
index
, since it deals with an array, we use the
variable
counter
here, as we do not have an array. You should note that
counter
is counting nodes
for loop control; it is not counting how many times a given entry occurs in a bag. Moreover, we
could omit
counter
entirely, but we retain it as a check on our logic.