Java Reference
In-Depth Information
The bag contains the following string(s):
A B A C B C D
Testing the method isFull with a full bag:
isFull finds the bag full: OK.
2.15
Notice that, in addition to the main method, ArrayBagDemo1 has three other methods. Since main is
static and calls these other methods, they must be static as well. The method testAdd accepts as its
arguments a bag and an array of strings. The method uses a loop to add each string in the array to
the bag. The method testIsFull takes a bag as its argument and a boolean value that indicates the
value we expect isFull to return if its logic is correct. Finally, the method displayBag takes a bag
as its argument and uses the bag's method toArray to access its contents. Once we have an array of
the bag's entries, a simple loop can display them.
Question 8 What is the result of executing the following statements within the main
method of BagDemo1 ?
ArrayBag<String> aBag = new ArrayBag<String>();
displayBag(aBag);
Implementing More Methods
Now that we can add objects to a bag, we can implement the remaining methods, beginning with the eas-
iest ones. We will postpone the definitions of remove momentarily until we see how to search a bag.
2.16
The methods isEmpty and getCurrentSize . The methods isEmpty and getCurrentSize have
straightforward definitions, as you can see:
/** Sees whether this bag is empty.
@return true if the bag is empty, or false if not */
public boolean isEmpty()
{
return numberOfEntries == 0;
} // end isEmpty
/** Gets the current number of entries in this bag.
@return the integer number of entries currently in the bag */
public int getCurrentSize()
{
return numberOfEntries;
} // end getCurrentSize
Note: The definitions of some methods are almost as simple as the stubs you might use to
define them in an early version of a class. Such is the case for the bag methods isEmpty and
getCurrentSize . Although these two methods are not in our first group of core methods,
they could have been. That is, we could have defined them earlier instead of writing stubs.
2.17
The method getFrequencyOf . To count the number of times a given object occurs in a bag, we count
the number of times the object occurs in the array bag . Using a for loop to cycle through the array's
indices from 0 to numberOfEntries - 1, we compare the given object to every object in the array.
 
 
Search WWH ::




Custom Search