Bag

import java.util.Iterator;

public class Bag<Item> implements Iterable<Item>{
    
    private Item[] items;        
    private int top;
    
    public Bag() {
        items = (Item[]) (new Object[1]);  
        top = 0; //superfluous
    }
    
    public boolean isEmpty() {
        return (top == 0);
    }
    
    public void resize(int capacity) {
        Item[] newArray = (Item[]) (new Object[capacity]);  
        for (int i = 0; i < top; i++) {
            newArray[i] = items[i];
        }
        items = newArray;
    }
    
    public void add(Item item) {   
        if (top == items.length) {
            resize( 2 * items.length );
        }
        items[top++] = item;
    }
    
    public int size() {
        return top;
    }
    
    // Traverse the bag elements from first added to last added.
    private class BagIterator implements Iterator<Item> {

        private int i = 0;

        public boolean hasNext() {
            return i < top;
        }

        public Item next() {
            return items[i++];
        }
    }
    
    public Iterator<Item> iterator() {
        return new BagIterator();
    }
}