Bag ADT


Note: the code shown on this page does not follow the commenting guidelines (or guidelines for whitespace) for CS 367; this page is meant to outline the Bag ADT (with additional information given in lecture).

Public interface / operations

import java.util.*;
public interface BagADT<E> {
    void add(E item);
    E remove() throws NoSuchElementException;
    boolean isEmpty();
    Iterator<E> iterator();
}

Implementing the Bag ADT using an array

import java.util.*;
public class ArrayBag<E> implements BagADT<E> {
    // *** Data members (fields) ***
    private E[] items;
    private int numItems;
    private static final int INIT_SIZE = 100;
    
    // *** Constructor ***
    public ArrayBag() {
        items = (E[])(new Object[INIT_SIZE]);
        numItems = 0;
    }
    
    // *** Bag ADT methods ***
    
    public void add(E item) {
        if (item == null) {
            throw new IllegalArgumentException("Bag does not allow null elements");
        } 
        if (numItems == items.length) { expandArray(); }
        items[numItems] = item;
        numItems++;
    }
    
    public E remove() throws NoSuchElementException {
        if (numItems < 1) { throw new NoSuchElementException(); }
        numItems--;
        return items[numItems];
    }

    public boolean isEmpty() { return numItems == 0; }
    
    public Iterator<E> iterator() {
 
 
  
 
    }
	
    // *** Private methods ***
    private void expandArray() { ... }
}