Java Reference
In-Depth Information
Question 1 Suppose aBag represents an empty bag that has a finite capacity. Write some
pseudocode statements to add user-supplied strings to the bag until it becomes full.
1.8
Three behaviors involve removing entries from a bag: remove all entries, remove any one entry,
and remove a particular entry. Suppose we name the methods and any parameters and specify them
in pseudocode as follows:
// Removes all entries from the bag.
clear()
// Removes one unspecified entry from the bag.
remove()
// Removes one occurrence of a particular entry from the bag, if possible.
remove(anEntry)
What return types are these methods?
1.9
The method clear can be a void method: We just want to empty the bag, not retrieve any of its con-
tents. Thus, we write
+clear(): void
in UML.
If the first remove method removes an entry from the bag, the method can easily return the
object it has removed. Its return type is then the generic type T . In UML, we have
+remove(): T
Notice that we can respond to an attempt to remove an object from an empty bag by returning null .
The second remove method won't be able to remove a particular entry from the bag if the bag does not
contain that entry. We could have the method return a boolean value, much as add does, so it can indicate
success or not. Or the method could return either the removed object or null if it can't remove the object.
Here are the specifications for these two possible versions of the method in UML —we must choose one:
+remove(anEntry: T): boolean
or
+remove(anEntry: T): T
If anEntry equals an entry in the bag, the first version of this method would remove that entry
and return true. Even though the method would not return the removed entry, the client would have
the method's argument, anEntry , which is equal to the removed entry. We will choose this first ver-
sion, to be consistent with the interface Collection .
Question 2 Is it legal to have both versions of remove(anEntry) , which were just described,
in one class? Explain.
Question 3 Is it legal to have two versions of remove , one that has no parameter and one
that has a parameter, in the same class? Explain.
Question 4 Given the full bag aBag that you created in Question 1, write some pseudocode
statements that remove and display all of the strings in the bag.
 
 
Search WWH ::




Custom Search