L05a

Due by the end of Wednesday, February 7

Starter Files:


SUBMIT   /   Submission Summary

Array Implementations

Activities 1 and 2
In class I explained how "arbitrary" means that there is no restriction on how something gets done. I also explained that, while doing things at random does count as arbitrary, there are easier ways to remove an arbitrary item from a Bag.

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! The remove() method you need is similar to the one I've provided in Bag. You can't use numInBag 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:

These two lists should be the same: [51, 24, 77] [51, 24, 77] And they are! These two lists should be different (probably): [55, 82, 9] [14, 59, 19] And they are! Threw NSEE as required.

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:


SUBMIT   /   Submission Summary