数组动态扩容

/**
 * 动态数组
 * @param <T>
 */
public class Array<T> {

    private T [] data;

    private int capacity;//容量

    private int size;// 数组数据大小

    public Array(int capacity){
        data = (T[]) new Object[capacity];
        size = 0;
        this.capacity = capacity;
    }

    public Array(){
        this(10);
    }

    public int  getSize(){
        return size;
    }

    public int getCapacity(){
        return capacity;
    }

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

    public void add(int index, T element){

        if (index < 0 || index > size)
            throw new IllegalArgumentException("index 越界 ");

        for (int i = size; i > index; i--){
            data[i] = data[i-1];
        }
        data[index] = element;
        size ++;
        if (size == capacity)
            resize(capacity * 2);
    }

    public void addFirst(T element){
        this.add(0,element);
    }

    public void addLast(T element){
        this.add(size,element);
    }

    public T get(int index){
        if (index < 0 || index >= size)
            throw new IllegalArgumentException("index 越界 ");
        return data[index];
    }

    public T remove(int index){
        T element = get(index);
        for (int i = index ; i < size; i++)
            data[i] = data[i +1];
        size --;
        if (size < capacity/4 && capacity/2 > 0)
            resize(capacity/2);
        return element;
    }

    public T removeLast(){
       return remove(size -1);
    }

    public T removeFirst(){
        return remove(0);
    }

    @Override
    public String toString(){
        StringBuilder ret = new StringBuilder();
        ret.append("Array  capacity: " +capacity + " size: " +size +"\n");
        ret.append("[");
        for (int i = 0 ; i< size; i++){
            ret.append(data[i]);
            if (i != size-1)
                ret.append(",");
        }
        ret.append("]");
        return ret.toString();
    }

    //给数组动态扩容或缩容
    public void resize(int newCapacity){
        T [] newArray = (T[]) new Object[newCapacity];
        for (int i = 0; i < size; i++ )
            newArray[i] = data[i];
        this.data = newArray;
        this.capacity = newCapacity;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值