Methods That Remove Strings
In this lesson, we define the remaining methods for the class BagOfStrings, those that remove entries.
We have postponed the methods to remove strings from a bag until now because defining a method to remove a specific string is somewhat more difficult and involves a search like the one we performed in the method contains. We begin, however, with the two methods that are not as difficult to define.
The method clear
The method clear removes all the strings from a bag, one at a time. The following definition of clear calls the method remove until the bag is empty:
/** Removes all strings from this bag. */
public void clear()
{
while (!isEmpty())
remove();
} // End clear
Exactly which string is removed by each cycle of the loop is unimportant. Thus, we call the remove method that removes an unspecified string. Moreover, we do not save the string that the method returns.
Revise the previous definition of the method clear so that it does not call isEmpty, and so the while statement has an empty body. Hint: What does remove return when the bag is empty?
We cannot test the method clear yet, because we have not defined the method remove.
But must clear call remove?
Can you think of a better way to implement clear, one that does not involve removing entries from the bag one at a time using the method remove? Describe such an approach.
Removing an unspecified string
The method remove that has no parameter removes any string from a bag, as long as the bag is not empty. Recall from its specification in the lesson Specifying a Bag that the method returns the string it removes. If the method cannot remove a string because the bag is empty, it returns null.
Removing a string from a bag involves removing it from an array. While we can access any string in the array bag, the last one is easy to remove. To do so, we:
- Get a reference to the string in
bag[numberOfStrings - 1]so it can be returned - Set
bag[numberOfStrings - 1]tonull - Decrement
numberOfStrings
Decrementing numberOfStrings causes the last entry to be ignored, meaning that it is effectively removed, even if we did not set its location in the array to null.
A literal translation of the previous steps into Java leads to the following definition of ...