CPSC 225, Fall 2007
Lab 12: A Generic Class

In this lab, you will write a very simple generic class, like those in Subsection 10.5.1. You will also write two short main programs to test your class with different type parameters.

You should be able to finish this lab during class. The lab is due, along with Lab 11 at noon on Wednesday, November 28. Please make sure that both labs are in your CVS repository by that time. Remember that you should be devoting most of effort to your final project.

A "Bag" class

Consider this problem: You have a bunch of items of a given type (strings, integer, dates, ...), where each item can appear multiple times in the group. This is something like a set, except that duplicate items are allowed. A data structure of this type is sometimes called a bag.

In order to represent a bag, you don't need to keep multiple copies of the same item. You just need to keep track of the number of times that that item occurs in the bag, If the items are all of type T, you can store the information in a map of type HashMap<T,Integer>. The integer associated with a value of type T is the number of times that value occurs in the bag. When adding an item to the bag, there are two cases: If it's the first copy of the item, then the item is added to the map with value 1. If another copy of the item is already in the bag, then the value of count is updated by adding 1 to its current value. Removing an item from the bag also has two cases. (To remove the last copy of an item from the bag, you can use the method map.remove(key) from the HashMap class; this method removes the specified key and its associated value from the map.)

Write a generic Bag class. You can begin the definition with "public class Bag<T> {...". Use an instance variable of type HashMap<T,Integer> to store the data for the bag. Include the following methods in your class:

Warning: Remember that for a HashMap<T,String>, map.get(key) returns an Integer, not an int. The return value can be null, indicating that the key does not occur in the map. Once you know that its value is not null, however, an Integer can be used in pretty much the same way as an int.

Write two simple main programs to test your Bag class. One main program should work with a variable of type Bag<String>, and one should work with a variable of type Bag<Integer>. Each program should simply create a bag, add some items to it, including some duplicates, remove some items, and then call the contains and count methods to make sure that they return the correct values.

David Eck, for CPSC 225