Thursday, June 14, 2012

HashBag

Data Structure

HashBag is a collection that knows the number of times an object appears in it. HashBag described here is an apache collection class. HashBag internally depends on HashMap. The Object to store becomes they Key and the no. of copies becomes the Value.



HashBag
HashBag






Add

First time the Object is added, its no. of copies will be initialized to 1.
HashBag
HashBag




















When an Object is added to the bag, it delegates the call to HashMap. The Object will be added as the Key, its hash code will be used to identify the array element.


HashBag
HashBag

















If we add an existing Object, its no. of copies will be incremented by the no. of copies added. If we just call add(Object) , no. of copies will be incremented by one.



HashBag
HashBag



HashBag
HashBag






Class Diagram


HashBag internally uses HashMap where the Object is the key and its value, a Mutable Integer to keep track of the count of objects in the collection.


HashBag
HashBag





























Home

No comments:

Post a Comment