数据结构笔记_动态数组的实现

public class Array {
    private E[] data;
    private int size;

    public Array(int capacity){
        data = (E[])new Object[capacity];  //不能直接new一个泛型数组,需要先new一个Object数组再强转为泛型数组。
    }
    public Array(){
        this(10);
    }

    public int getSize(){
        return size;
    }

    public int getCapacity(){
        return data.length;
    }

    public boolean isEmpty(){
        return size==0;
    }

    public void add(int index, E e){
        if (index <0 || index>size){
            throw new IllegalArgumentException("Add failed! Require index>=0 and index<=size.");
        }

        if (size==data.length){
            resize(2*data.length);
        }

        for (int i=size-1; i>=index; i--){
            data[i+1]=data[i];
        }
        data[index]=e;
        size++;
    }

    public void addFirst(E e){
        add(0,e);
    }

    public void addLast(E e){
        add(size,e);
    }

    public E get(int index){
        if (index<0 || index>=size){
            throw new IllegalArgumentException("Get failed! Index is illegal.");
        }

        return data[index];
    }

    public void set(int index, E e){
        if(index<0 || index>=size){
            throw new IllegalArgumentException("Set failed! Index is illegal.");
        }

        data[index]=e;
    }

    public boolean contains(E e){
        for (int i=0; i=size){
            throw new IllegalArgumentException("Remove failed! Index is illegal.");
        }

        E ret=data[index];
        for (int i=index+1; i

 

你可能感兴趣的:(数据结构)