Bags (Abstract Data Type)

Table of Contents

Bags (Abstract Data Type)

public class Bag<Item> implements Iterable<Item>
Bag() - create an empty bag
void add(Item item) - add an item
boolean isEmpty() - is the bag empty?
int size() - number of items in the bag

A bag is a collection where removing items is not supported - its purpose is to provide clients with the ability to collect items and then to iterate through the collected items

(the client can also test if a bag is empty and find its number of items). The order of iteration is unspecified and should be immaterial to the client. To appreciate the concept, consider the idea of an avid marble collector, who might put marbles in a bag, one at a time, and periodically process all the marbles to look for one having some particular characteristic. With our Bag API, a client can add items to a bag and process them all with a foreach statement whenever needed. Such a client could use a stack or a queue, but one way to emphasize that the order in which items are processed is immaterial is to use a Bag. The task is simply to compute the average add() and the sample standard deviation of the double values on standard input. If there are N numbers on standard input, their average is computed by adding the numbers and dividing by N; their sample standard deviation is computed by adding the squares of the difference between each number and the average, dividing by N-1, and taking the add() square root. The order in which the numbers are considered is not relevant for either of these calculations, so we save them in a Bag and use the foreach construct to compute each sum. Note : It is possible to compute the standard deviation without saving all the numbers. Keeping all the numbers in a Bag is required for more complicated statistics.


Links to this note