Due by the end of Wednesday, February 7
But sometimes we do want random behaviour.
Consider,
for example,
a Hat,
which is like a Bag
(in that it does not matter what order the elements appear in,
and it allows duplicates),
but the remove()
method
removes a thing at random.
I have provided you with a version of ArrayBag
in which the removeItemAt
method
has been marked as protected
instead of private
.
When a method (or instance variable) is marked protected
,
that means that subclasses are allowed to access that method
(or instance variable).
Extend this modified ArrayBag class
to create a Hat class.
The only method that needs to be overridden
is the remove()
method.
Don't make this hard! Theremove()
method you need is similar to the one I've provided in Bag. You can't usenumInBag
directly, and you need to choose the item to remove randomly, but that's it as far as differences go.
If the Hat is empty,
remove()
throws a NoSuchElementException
(just as Bag did).
Otherwise,
it uses its Random's nextInt(int)
to generate the index of the item to be removed.
(nextInt(upperBound)
returns a number in the range
from 0 to upperBound - 1.)
Give the Hat class two constructors:
Run the program TestHat to test your code. You should see output like this:
Note that the second pair of lists will almost certainly (99,999 times in 100,000) come out different from what's shown above (and from each other). I'd be very surprised if the first pair of lists came out any different from what's shown above.
For the purposes of the grading scheme,
the remove()
method is the first activity,
and the constructors form the second activity.
Submit your Hat class by the end of this recitation. (You do not need to submit your testing code; we know what your code is supposed to do!)
Your grade will be based on the following rubric:
Submit this/these files: