動態(tài)數(shù)組

  • Java實現(xiàn):
/**
 * 動態(tài)數(shù)組
 *
 * @param <E> 元素類型
 * @author ZhuZongxing
 */
public class Array<E> {
    private E[] mData;
    private int mSize;

    public Array(int capacity) {
        //TODO 類型強轉(zhuǎn)不安全如何解決
        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;
    }

    /**
     * 根據(jù)下標(biāo)刪除元素
     *
     * @param index 下標(biāo)
     * @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;
        //四分之一是防止復(fù)雜度震蕩,即當(dāng)數(shù)組滿了的時候不斷加減一個元素,會導(dǎo)致不停resize()導(dǎo)致性能變差
        if (mSize == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }
        return ret;
    }

    /**
     * 從數(shù)組中刪除元素e(包括重復(fù)的)
     *
     * @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;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容