// File:  ADTList\ArrayList.java

/**
 * Realization of a List ADT
 * 
 * @author Bary W Pollack
 * @version Dec. 31, 2000 - 23:00 PST
 */

// Represents an array implementation of a list of ints
public class ArrayList extends List {

    // Default constructor
    ArrayList() { }

    // Creates a fresh array-implemented list of a given length
    public void create(int length) {
        list = new NItem[length];
        this.length = 0;
    }

    // True if the list cannot contain any more Items
    public boolean isFull() throws ListException {
        checkNullList();
        return (length >= list.length);
    }

    // Returns the number of Items in the list
    public int size() throws ListException {
        checkNullList();
        return length;
    }
    
    // Adds the Item at location index, moving the rest down
    public void add(int index, NItem nItem) throws ListException {
        checkNullList();
        if (index < 0 || index > length || index >= list.length)
            throw new ListException("index out of range (" + index + ")");
        if (length >= list.length)
            throw new ListException("list full (" + length + ")");
        for (int i = length-1  +1; i > index; i--)
            list[i] = list[i-1];
        list[index] = nItem;
        ++length;
    }

    // Removes the Item at list[index]
    public void remove(int index) throws ListException {
        checkNullList();
        checkIndex(index);
        if (index >= length)
            throw new ListException("index out of range (" + index + ")");
        for (int i = index; i < length-1; i++)
            list[i] = list[i+1];
        --length;
    }

    // Empties the list
    public void removeAll() {
        create(list.length); 
    }

    // Retrieves a copy of the NItem at list[index]
    public Item get(int index) throws ListException {
        checkNullList();
        checkIndex(index);
        return list[index];
    }

    // Displays the list on System.out
    public void display() throws ListException {
        checkNullList();
        System.out.println(toString());
    }

    // Checks to ensure that 'list' is not null
    protected void checkNullList() throws ListException {
        if (list == null)
            throw new ListException("list is <null>");
    }

    protected NItem[] list;
    protected int length;
}
