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())
} // 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.

Get hands-on with 1200+ tech skills courses.