天天看點

【Java8源碼分析】集合架構-ArrayList

一、總結

(1)ArrayList随機元素時間複雜度O(1),插入删除操作需大量移動元素,效率較低

(2)為了節約記憶體,當建立容器為空時,會共享

Object[] EMPTY_ELEMENTDATA = {}

Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}

空數組

(3)容器底層采用數組存儲,每次擴容為1.5倍

(4)ArrayList的實作中大量地調用了

Arrays.copyof()

System.arraycopy()

方法,其實

Arrays.copyof()

内部也是調用

System.arraycopy()

System.arraycopy()

為Native方法

(5)兩個ToArray方法

  • Object[] toArray()

    方法。該方法有可能會抛出java.lang.ClassCastException異常
  • <T> T[] toArray(T[] a)

    方法。該方法可以直接将ArrayList轉換得到的Array進行整體向下轉型

(6)ArrayList可以存儲null值

(7)ArrayList每次修改(增加、删除)容器時,都是修改自身的modCount;在生成疊代器時,疊代器會儲存該modCount值,疊代器每次擷取元素時,會比較自身的modCount與ArrayList的modCount是否相等,來判斷容器是否已經被修改,如果被修改了則抛出異常(fast-fail機制)。

二、源碼和注解

package java.util;

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = L;

    // 預設初始大小
    private static final int DEFAULT_CAPACITY = ;

    // 指定大小的空的ArrayList共享此對象
    private static final Object[] EMPTY_ELEMENTDATA = {};

    // 預設大小的空的ArrayList共享
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    // 存儲容器,為數組
    transient Object[] elementData;

    // 存放容器大小
    private int size;

    // 傳入初始大小
    public ArrayList(int initialCapacity) {
        if (initialCapacity > ) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == ) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    // 無參構造
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    // 由Collection構造
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != ) {
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    // 将目前容量設為實際元素個數
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == )
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

    // 確定容器容量,當容器非空時,不得小于預設大小
    public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            ? 
            : DEFAULT_CAPACITY;
        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        ensureExplicitCapacity(minCapacity);
    }

    // 注意此方法在每次添加元素時調用,確定容量足夠,且更改modCount
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        if (minCapacity - elementData.length > )
            grow(minCapacity);
    }

    // 數組最大元素個數,因為部分虛拟機會為數組預留了頭部,故這裡減8保證不會記憶體溢出
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - ;

    // 擴容為minCapacity或者舊容器大小*1.5中較大的一個
    private void grow(int minCapacity) {
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> );
        if (newCapacity - minCapacity < )
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > )
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < ) // 溢出
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

    public int size() {
        return size;
    }

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

    // 周遊所有元素的方法,效率較低
    public boolean contains(Object o) {
        return indexOf(o) >= ;
    }

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

    public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-; i >= ; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-; i >= ; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -;
    }

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

    // 該方法有可能會抛出java.lang.ClassCastException異常,
    // 如果直接用向下轉型的方法,将整個ArrayList集合轉變為指定類型的Array數組,便會抛出該異常
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    // 該方法可以直接将ArrayList轉換得到的Array進行整體向下轉型
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, , a, , size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

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

    // 随機通路
    public E get(int index) {
        rangeCheck(index);
        return elementData(index);
    }

    // 随機存儲
    public E set(int index, E element) {
        rangeCheck(index);
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

    // 末尾添加元素
    public boolean add(E e) {
        ensureCapacityInternal(size + );  // 改變modCount
        elementData[size++] = e;
        return true;
    }

    // 随機位置添加元素,需複制後續元素,效率較低
    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + );
        // 複制插入位置的後續元素
        System.arraycopy(elementData, index, elementData, index + ,
                         size - index);
        elementData[index] = element;
        size++;
    }

    public E remove(int index) {
        rangeCheck(index);

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

        int numMoved = size - index - ;
        if (numMoved > )
            System.arraycopy(elementData, index+, elementData, index,
                             numMoved);
        // 設定不通路的元素為null,觸發gc
        elementData[--size] = null;

        return oldValue;
    }

    // 删除第一個出現的元素
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = ; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = ; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

    // 快速删除,在確定下标正确的情況下,不檢查下标範圍
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - ;
        if (numMoved > )
            System.arraycopy(elementData, index+, elementData, index,
                             numMoved);
        elementData[--size] = null;
    }

    // 清楚所有元素,設定為null,但存儲的elementData容量不變
    public void clear() {
        modCount++;

        for (int i = ; i < size; i++)
            elementData[i] = null;

        size = ;
    }

    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount
        System.arraycopy(a, , elementData, size, numNew);
        size += numNew;
        return numNew != ;
    }

    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount

        int numMoved = size - index;
        if (numMoved > )
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);

        System.arraycopy(a, , elementData, index, numNew);
        size += numNew;
        return numNew != ;
    }

    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private void rangeCheckForAdd(int index) {
        if (index > size || index < )
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = , w = ;
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }

    // java.io.Serializable的寫入函數    
    // 将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=; i<size; i++) {
            s.writeObject(elementData[i]);
        }

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

    // java.io.Serializable的讀取函數:根據寫入方式讀出    
    // 先将ArrayList的“容量”讀出,然後将“所有的元素值”讀出 
    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 > ) {
            // 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=; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }
}
           

三、參考

http://blog.csdn.net/ns_code/article/details/35568011