抽象数据类型之表(不断更新)

来源:互联网 发布:联通iptv网络电视 编辑:程序博客网 时间:2024/06/05 05:39

// List.java
public interface List {
    boolean isEmpty();
    int size();
    void add(int index, int item);
    void remove(int index);
    void removeAll();
    int get(int index);
    void print();
}

// SequenceList.java
public class SequenceList implements List {
    public SequenceList() {
        items = new int[MAX_SIZE];
        size = 0;
    }
 
    public boolean isEmpty() {
        return size == 0;
    }
 
    public int size() {
        return size;
    }
 
    public void add(int index, int item) {
        if (size == MAX_SIZE)
            throw new IllegalStateException("Full, cannot ADD more items");
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: " + index);
  
        if (index < size)
            for (int i = size - 1; i >= index; i--)
                items[i + 1] = items[i];
  
        items[index] = item;
        size++;
    }
 
    public void remove(int index) {
        if (size == 0)
            throw new IllegalStateException("Empty, cannot REMOVE more items");
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: " + index);


        for (int i = index + 1; i < size; i++)
            items[i - 1] = items[i];
        size--;
    }
 
    public void removeAll() {
        items = new int[MAX_SIZE];
        size = 0;
    }
 
    public int get(int index) {
        if (size == 0)
            throw new IllegalStateException("Empty, cannot GET more items");
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: " + index);

        return items[index];
    }
 
    private int[] items;
    private int size;
    private static final int MAX_SIZE = 50;
}