Android开发Android进阶之路Android开发

动态数组

2019-12-31  本文已影响0人  ZhuZongxing
/**
 * 动态数组
 *
 * @param <E> 元素类型
 * @author ZhuZongxing
 */
public class Array<E> {
    private E[] mData;
    private int mSize;

    public Array(int capacity) {
        //TODO 类型强转不安全如何解决
        mData = (E[]) new Object[capacity];
        mSize = 0;
    }

    public Array() {
        this(10);
    }

    public int getSize() {
        return mSize;
    }

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

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

    public boolean add(int index, E e) {
        if (index < 0) {
            throw new IllegalArgumentException("非法index");
        }
        if (mSize == getCapacity()) {
            //扩容
            resize(2 * getCapacity());
        }
        for (int i = mSize - 1; i >= index; i--) {
            mData[i + 1] = mData[i];
        }
        mData[index] = e;
        mSize++;
        return true;
    }

    public E get(int index) {
        if (index < 0 || index >= mSize) {
            throw new IllegalArgumentException("非法index");
        }
        return mData[index];
    }

    public boolean set(int index, E e) {
        if (index < 0 || index >= mSize) {
            return false;
        }
        mData[index] = e;
        return true;
    }

    public boolean contains(E e) {
        for (E temp : mData) {
            if (temp == e) {
                return true;
            }
        }
        return false;
    }

    /**
     * 根据下标删除元素
     *
     * @param index 下标
     * @return 被删除的元素
     */
    public E remove(int index) {
        if (index < 0 || index >= mSize) {
            throw new IllegalArgumentException("非法index");
        }
        E ret = mData[index];
        for (int i = index; i < mSize - 1; i++) {
            mData[i] = mData[i + 1];
        }
        mSize--;
        mData[mSize] = null;
        //四分之一是防止复杂度震荡,即当数组满了的时候不断加减一个元素,会导致不停resize()导致性能变差
        if (mSize == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }
        return ret;
    }

    /**
     * 从数组中删除元素e(包括重复的)
     *
     * @param e 要删除的元素
     * @return 是否删除成功
     */
    public boolean removeAllElement(E e) {
        for (int i = mSize - 1; i >= 0; i--) {
            if (e == mData[i]) {
                remove(i);
            }
        }
        return true;
    }

    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity];
        for (int i = 0; i < mSize; i++) {
            newData[i] = mData[i];
        }
        mData = newData;
    }
}
上一篇下一篇

猜你喜欢

热点阅读