java之ArrayList源碼解析

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

  //默認列表長度
  	private static final int DEFAULT_CAPACITY=10;
  	//空列表被共享
  	private static final Object[] EMPTY_ELEMENTDATA = {};
  	//用來存儲列表數據元素的數組
  	private transient Object[] elementData;
  	//ArrayList當前存儲數據長度
  	private int size;
    /**
     * 構造指定初始容量的列表數組
     */
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }
    /**
     * 無參構造函數,指定默認爲空的列表數組
     */
    public ArrayList() {
        super();
        this.elementData = EMPTY_ELEMENTDATA;
    }

    /**
     * 將集合元素初始化到列表數組中,並且指定長度爲集合元素個數
     */
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }
    /**
     * modCount是指定列表數組結構發生改變的次數
     * trimToSize()將,釋放列表數組中沒有使用的空間,將數組長度指定爲當前元素的個數,通過數組copy,只有確定數組不在添加元素在調用,
     * 負責每次copy數組效率非常低。
     */
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = Arrays.copyOf(elementData, size);
        }
    }
    /**
     * ensureCapacity()用於容量自動擴充,首先判斷調用ensureCapacity()方法的是否是創建初始數組,如果是有可能沒有指定初始容量,則將初始容量
     * 指定爲10,如果指定了初始容量大於10,則根據指定的初始容量進行擴容。
     * 如果是非空列表數組調用ensureCapacity()則對其進行擴容(將其賦爲0就是確保肯定能夠擴容),根據指定多的大小調用ensureExplicitCapacity()方法進行擴容
     * ensureExplicitCapacity確保確保指定的容量大於當前數組存儲元素的個數,然後調用grow()進行擴容,擴容容量增加爲原來的二倍,如果傳遞的指定的minCapacity容量
     * 比其二倍還要多,則使用指定大小的容量,如果擴容之後的容量大於int類型能夠表示的大小,則直接將其大小賦值爲Integer.MAX_VALUE
     */
    public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != EMPTY_ELEMENTDATA)
            // any size if real element table
            ? 0
            // larger than default for empty table. It's already supposed to be
            // at default size.
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == 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);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
    /**
     * 返回當前存儲數據元素的個數
     */
    public int size() {
        return size;
    }
    /**
     * 判斷其當前爲數組是否爲空,就是判斷當前元素個數是否爲0
     */
    public boolean isEmpty() {
        return size == 0;
    }
    /**
     * 指定元素是否包含在數組中,是通過indexOf()方法進行判斷,指定元素位置的,如果不存在返回-1
     */
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
    /**
     * 判斷指定對象是否在數組當中,其返回的是首次出現該元素的位置,indexOf()會首先判斷傳遞的元素是否爲null,如果是和null進行比較
     * 否則使用o.equals(elementData[i])和元素進行比較,如果沒有找到則返回-1,找到返回其出現的下標位置
     */
    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;
    }
    /**
     * lastIndexOf(Object o)通過反向進行查找,查找該元素最後一次出現在列表的位置,判斷原理和IndexOf()一樣,只不過for循環反向遍歷
     */
    public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
    /**
     * 通過輕複製進行列表克隆
     */
    public Object clone() {
        try {
            @SuppressWarnings("unchecked")
                ArrayList<E> v = (ArrayList<E>) 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();
        }
    }
    /**
     * 將列表轉換稱數組,其實就是進行元素複製,複製返回一個數組對象
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }
    /**
     * 指定要轉換的數組,如果這個數組容量不足,則返回一個新的數組,否則就將列表元素複製到這個數組當中
     */
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }
    /**
     * 通過elementData返回指定位置的數組元素
     */
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }
    /**
     * get獲取指定位置的元素,其實調用elementData方法,就是直接取出數組特定索引的元素
     * 首先會進行判斷指定位置是否有可能超過數組長度
     */
    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }
    /**
     * 通過set更改指定位置元素的值,返回原先值
     */
    public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
    /**
     * 列表元素添加,首先通過ensureCapacityInternal判斷是否需要擴容,是通過當前元素個數加上要添加的元素與當前數組長度進行比較,即minCapacity - elementData.length
     * 如果大於當前數組長度,則進行擴容,然後在列表最後添加元素
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    /**
     * 在指定位置添加元素,也會判斷位置,容量。
     * 然後將指定位置之後的元素全體向後移動一個位置,然後在指定位置添加元素,這個算法時間複雜度O(n),應儘量少使用
     */
    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++;
    }
    /**
     * 刪除指定位置元素,首先判斷位置,取出要刪除的值作爲方法的返回值。然後將指定位置後的元素全體向前移動一位,然後長度當前元素個數減1,最後位置複製null
     */
    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;
    }
    /**
     * 刪除指定元素,還是首先進行判斷要刪除的值是否爲null,決定和什麼進行比較。
     * 找到指定元素後調用fastRemove()方法,將當前索引下標傳遞過去,然後就和刪除指定位置元素一樣了
     */
    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
    }

    /**
     * 清空數組列表,將其全部賦值爲null,然後長度設置爲0
     */
    public void clear() {
        modCount++;
        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        size = 0;
    }

    /**
     * 將指定集合元素添加到列表末尾,首先根據集合長度也要判斷數組列表是否需要進行擴容,然後將集合元素copy到列表末尾,再將元素個數加上
     * 集合元素個數
     */
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

    /**
     * 指定位置添加集合中全部元素,首先要爲集合元素空出位置,將列表中index後元素全體向後移動集合個數的長度,然後將集合中元素添加到列表當中
     */
    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 > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);

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

    /**
     * 刪除指定區間元素,將區間toindex後的全體元素向前移動刪除區間長度的單位,然後將列表中移動之後的位置元素設置爲null,列表元素個數
     * 爲原列表元素個數減去刪除的元素個數
     */
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // clear to let GC do its work
        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 < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    /**
     * 刪除列表中包含指定集合中的元素,removeAll通過調用batchRemove()方法,barchRemove通過傳遞一個boolean值確定是retainAll
     * 調用還是removeAll調用,retainAll是將不包含在集合中的元素在列表中刪除
     */
    public boolean removeAll(Collection<?> c) {
        return batchRemove(c, false);
    }
    public boolean retainAll(Collection<?> c) {
        return batchRemove(c, true);
    }
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        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;
    }
    /**
     * 返回ListIterator實例,可以進行ListIterator迭代操作,從指定位置開始進行迭代
     */
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    /**
     * 從從列表其實位置進行迭代
     */
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    /**
     * 返回Iterator迭代器
     */
    public Iterator<E> iterator() {
        return new Itr();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章