java ArrayList原理與應(yīng)用

ArrayList 特有的方法(一般也是用的其父類List的方法):
ensureCapacity(int minCapacity) //初始化容量
trimToSize()  //清除剩余容量
筆試題目:

使用ArrayList無參的構(gòu)造函數(shù)創(chuàng)建一個 對象時, 默認(rèn)的容量是多少? 如果長度不夠使用時又自增增長多少?

    ArrayList底層是維護了一個Object數(shù)組實現(xiàn) 的,使用無參構(gòu)造函數(shù)時,Object數(shù)組默認(rèn)的容量是10,當(dāng)長度不夠時,自動增長0.5倍。
原理剖析:
私有變量:
    private transient Object[] elementData;//維護的Object數(shù)組
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//ArrayList最大容量
構(gòu)造方法:
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0) //容量小于0拋出異常
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];//創(chuàng)建對應(yīng)容量數(shù)組
    }

    public ArrayList() {
        this(10);  //默認(rèn)容量10
    }

添加數(shù)據(jù)方法:
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    private void ensureCapacityInternal(int minCapacity) {
        modCount++;
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
  /*如果最小需求容量 - 當(dāng)前空間容量 > 0 代表"當(dāng)前容量不夠"*/

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);//a >> n =a / 2^n
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
    /*newCapacity = oldCapacity + oldCapacity/2
    如果newCapacity還是小于oldCapacity,那么新容量就用oldCapacity
    如果newCapacity大于了最大容量,那么就會進行大容量處理*/

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
最后編輯于
?著作權(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)容