Bag ADT


Conceptual picture

 

 

 

Public interface / operations

 

    void add(Object item)
    Object remove() throws NoSuchElementException
    boolean isEmpty()
    

Using the Bag ADT

Example 1

Given an empty BagADT named bag, write a code fragment to put the numbers 0 through 99 into the Bag.

 

 

 

 

 

 

 

Example 2

Complete the printBag method so that it prints the contents of the parameter bag. Challenge: implement your printBag method so that it doesn't change the bag's contents.

public static void printBag(BagADT bag) {

 

 

 

 

 

 

 

Example 3

Consider the following code (where bag is a BagADT) meant to roll each die in the Bag:

for (int i = 0; i < 10; i++) {
    bag.add(new Die());
}
 
while (!bag.isEmpty()) {
    Die myDie = bag.remove();
    myDie.roll();
}

 

 

 

 

 

 

 

 

 

 

Implementing the Bag ADT using an array of Objects

public class ArrayBag implements BagADT {













Java generics

import java.util.*;
 
public interface BagADT   {

    void add(Object item);

    Object remove() throws NoSuchElementException;

    boolean isEmpty();
}