【數據結構】ArrayList原理及實現學習總結(2)

ArrayList是一個基於數組實現的鏈表(List),這一點能夠從源碼中看出:java

    transient Object[] elementData; // non-private to simplify nested class access

能夠看出ArrayList的內部是給予數組來處理的。數組

從ArrayList中查找一個元素的index,其時間複雜度是o(n),其源碼以下所示:安全

複製代碼
    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
複製代碼

ArrayList支持Clone,是使用Arrays.copyOf(Object[],int)來進行的:app

複製代碼
    public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }
複製代碼

ArrayList中根據index獲取數組的時間複雜度是o(1),其源碼以下:this

複製代碼
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    public E get(int index) {//看這裏
        rangeCheck(index);

        return elementData(index);
    }
複製代碼

替換指定的位置的元素,時間複雜度也是o(1):spa

複製代碼
    public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
複製代碼

在末尾添加一個元素的時間複雜度也是o(1):線程

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

這裏須要注意的是,其容量是能夠擴展的,其能夠擴展的最大容量是Integer.MAX_VALUE-8,由code

int newCapacity = oldCapacity + (oldCapacity >> 1)

能夠看出,每次是嘗試擴容原來的1.5倍:對象

複製代碼
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        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);
    }
複製代碼

添加到指定index位置的時間複雜度是o(n),這裏須要先把這個位置以及以後的元素統一貫後移一位:blog

複製代碼
    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }
複製代碼

刪除指定index位置的元素時間複雜度也是o(n),這裏須要把這個元素以後的全部的元素向前移一位:

複製代碼
    public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }
複製代碼

刪除一個元素的時間複雜度也是o(n),顯示查出來這個元素,刪除,以後是把後面的元素向前進一位:

複製代碼
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }
複製代碼

雖然在申明存儲數組的時候,申明瞭不可被序列化,可是隻要保存的對象是可序列化的,這個ArrayList仍是能夠序列化的:

複製代碼
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        // Write out element count, and any hidden stuff
        int expectedModCount = modCount;
        s.defaultWriteObject();

        // Write out size as capacity for behavioural compatibility with clone()
        s.writeInt(size);

        // Write out all elements in the proper order.
        for (int i=0; i<size; i++) {
            s.writeObject(elementData[i]);
        }

        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        elementData = EMPTY_ELEMENTDATA;

        // Read in size, and any hidden stuff
        s.defaultReadObject();

        // Read in capacity
        s.readInt(); // ignored

        if (size > 0) {
            // be like clone(), allocate array based upon size not capacity
            ensureCapacityInternal(size);

            Object[] a = elementData;
            // Read in all elements in the proper order.
            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }
複製代碼

 從以上的狀況來看,ArrayList不是線程安全的,在進行index查找和最後插入的時候具備比較明顯的時間複雜度優點。

可是,ArrayList的擴容操做,以及擴容產生的空間浪費一直是被人詬病的地方,另外在其中間進行插入的操做也不盡人意,時間複雜度是o(n)。

相關文章
相關標籤/搜索