Java Reference
In-Depth Information
Question 9 The method contains could call getFrequencyOf instead of executing a loop.
That is, you could define the method as follows:
public boolean contains(T anEntry)
{
return getFrequencyOf(anEntry) > 0;
} // end contains
What is an advantage and a disadvantage of this definition as compared to the one given in the pre-
vious segment?
Note: Two kinds of loops
To count how many times an entry occurs in an array, the method getFrequencyOf uses a
loop that cycles through all of the array's entries. In fact, the body of the loop executes
numberOfEntries times. In contrast, to indicate whether a given entry occurs in an array,
the loop in the method contains ends as soon as the desired entry is discovered. The body
of this loop executes between one and numberOfEntries times. You should be comfortable
writing loops that execute either a definitive or a variable number of times.
2.19
Testing the additional methods. As you define additional methods for the class ArrayBag , you
should test them. The program ArrayBagDemo2 , which is available online from the topic's website,
focuses only on these additional methods. However, you should form a test program incrementally so
that it tests all the methods you have defined so far. The tests in ArrayBagDemo2 are performed on a
bag that is not full and on a full bag, as we did in ArrayBagDemo1 . The version of the class ArrayBag
to date is named ArrayBag2 within the source code available online.
Methods That Remove Entries
We have postponed the three methods that remove entries from a bag until now because one of them is
somewhat difficult and involves a search much like the one we performed in the method contains . We
begin with the two methods that are easier to define.
2.20
The method clear . The method clear removes all entries from a bag, one at a time. The following
definition of clear calls the method remove until the bag is empty:
/** Removes all entries from this bag. */
public void clear()
{
while (!isEmpty())
remove();
} // end clear
Exactly which entry is removed by each cycle of the loop is unimportant. Thus, we call the remove
method that removes an unspecified entry. Moreover, we do not save the entry that the method returns.
Note: We can write the definition of the method clear in terms of the as yet undefined
method remove . However, we cannot test clear completely until remove is defined.
 
 
Search WWH ::




Custom Search