ArrayList源碼分析

以下資料整理自互聯(lián)網(wǎng),僅用于個(gè)人學(xué)習(xí)


ArrayList簡介

ArrayList是基于數(shù)組實(shí)現(xiàn)的,是一個(gè)動(dòng)態(tài)數(shù)組,其容量能自動(dòng)增長。

ArrayList不是線程安全的,多線程情況下可以考慮用collections.synchronizedList(List l)函數(shù)返回一個(gè)線程安全的ArrayList類,也可以使用concurrent并發(fā)包下的CopyOnWriteArrayList類。

ArrayList實(shí)現(xiàn)了Serializable接口,因此它支持序列化。實(shí)現(xiàn)了RandomAccess接口,支持快速隨機(jī)訪問,實(shí)際上就是通過下標(biāo)快速訪問。實(shí)現(xiàn)了Cloneable接口,能進(jìn)行克隆。


源碼分析

package java.util;    

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

    // ArrayList基于該數(shù)組實(shí)現(xiàn),用該數(shù)組保存數(shù)據(jù)   
    private transient Object[] elementData;    

    // ArrayList中實(shí)際數(shù)據(jù)的數(shù)量    
    private int size;    

    // ArrayList帶容量大小的構(gòu)造函數(shù)。    
    public ArrayList(int initialCapacity) {    
        super();    
        if (initialCapacity < 0)    
            throw new IllegalArgumentException("Illegal Capacity: "+    
                                               initialCapacity);    
        // 新建一個(gè)數(shù)組    
        this.elementData = new Object[initialCapacity];    
    }    

    // ArrayList無參構(gòu)造函數(shù)。默認(rèn)容量是10。    
    public ArrayList() {    
        this(10);    
    }    

    // 創(chuàng)建一個(gè)包含collection的ArrayList    
    public ArrayList(Collection<? extends E> c) {    
        elementData = c.toArray();    
        size = elementData.length;    
        if (elementData.getClass() != Object[].class)    
            elementData = Arrays.copyOf(elementData, size, Object[].class);    
    }    


    // 將當(dāng)前容量值設(shè)為實(shí)際元素個(gè)數(shù)    
    public void trimToSize() {    
        modCount++;    
        int oldCapacity = elementData.length;    
        if (size < oldCapacity) {    
            elementData = Arrays.copyOf(elementData, size);    
        }    
    }    


    // 確定ArrarList的容量。    
    public void ensureCapacity(int minCapacity) {    
        // 將“修改統(tǒng)計(jì)數(shù)”+1,該變量主要是用來實(shí)現(xiàn)fail-fast機(jī)制的    
        modCount++;    
        int oldCapacity = elementData.length;    
        // 若當(dāng)前容量不足以容納當(dāng)前的元素個(gè)數(shù),設(shè)置 新的容量=“(原始容量x3)/2 + 1”    
        if (minCapacity > oldCapacity) {    
            Object oldData[] = elementData;    
            int newCapacity = (oldCapacity * 3)/2 + 1;    
            //如果還不夠,則直接將minCapacity設(shè)置為當(dāng)前容量  
            if (newCapacity < minCapacity)    
                newCapacity = minCapacity;    
            elementData = Arrays.copyOf(elementData, newCapacity);    
        }    
    }    

    // 返回ArrayList的實(shí)際大小    
    public int size() {    
        return size;    
    }    

    // ArrayList是否包含Object(o)    
    public boolean contains(Object o) {    
        return indexOf(o) >= 0;    
    }    

    //返回ArrayList是否為空    
    public boolean isEmpty() {    
        return size == 0;    
    }    

    // 正向查找,返回元素的索引值    
    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;    
        }      
    }    

    // 反向查找(從數(shù)組末尾向開始查找),返回元素(o)的索引值    
    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;    
    }    


    // 返回ArrayList的Object數(shù)組    
    public Object[] toArray() {    
        return Arrays.copyOf(elementData, size);    
    }    

    // 返回ArrayList元素組成的數(shù)組  
    public <T> T[] toArray(T[] a) {    
        // 若數(shù)組a的大小 < ArrayList的元素個(gè)數(shù);    
        // 則新建一個(gè)T[]數(shù)組,數(shù)組大小是“ArrayList的元素個(gè)數(shù)”,并將“ArrayList”全部拷貝到新數(shù)組中    
        if (a.length < size)    
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());    

        // 若數(shù)組a的大小 >= ArrayList的元素個(gè)數(shù);    
        // 則將ArrayList的全部元素都拷貝到數(shù)組a中。    
        System.arraycopy(elementData, 0, a, 0, size);    
        if (a.length > size)    
            a[size] = null;    
        return a;    
    }    

    // 獲取index位置的元素值    
    public E get(int index) {    
        RangeCheck(index);    

        return (E) elementData[index];    
    }    

    // 設(shè)置index位置的值為element    
    public E set(int index, E element) {    
        RangeCheck(index);    

        E oldValue = (E) elementData[index];    
        elementData[index] = element;    
        return oldValue;    
    }    

    // 添加元素e    
    public boolean add(E e) {    
        // 確定ArrayList的容量大小    
        ensureCapacity(size + 1);  // Increments modCount!!    
        // 添加e到ArrayList中    
        elementData[size++] = e;    
        return true;    
    }  

    // 將e添加到ArrayList的指定位置    
    public void add(int index, E element) {    
        if (index > size || index < 0)    
            throw new IndexOutOfBoundsException(    
            "Index: "+index+", Size: "+size);    

        ensureCapacity(size+1);  // Increments modCount!!    
        System.arraycopy(elementData, index, elementData, index + 1,    
             size - index);    
        elementData[index] = element;    
        size++;    
    }    

    // 刪除ArrayList指定位置的元素    
    public E remove(int index) {    
        RangeCheck(index);    

        modCount++;    
        E oldValue = (E) elementData[index];    
        // 從"index+1"開始,用后面的元素替換前面的元素。
        int numMoved = size - index - 1;    
        if (numMoved > 0)    
            System.arraycopy(elementData, index+1, elementData, index,    
                 numMoved);    
        elementData[--size] = null; // Let gc do its work    

        return oldValue;    
    }    

    // 刪除ArrayList的指定元素    
    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;    
    }    


    // 快速刪除第index個(gè)元素    
    private void fastRemove(int index) {    
        modCount++;    
        int numMoved = size - index - 1;    
        // 從"index+1"開始,用后面的元素替換前面的元素。    
        if (numMoved > 0)    
            System.arraycopy(elementData, index+1, elementData, index,    
                             numMoved);    
        // 將最后一個(gè)元素設(shè)為null    
        elementData[--size] = null; // Let gc do its work    
    }    

    // 清空ArrayList,將全部的元素設(shè)為null    
    public void clear() {    
        modCount++;    

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

        size = 0;    
    }    

    // 將集合c追加到ArrayList中    
    public boolean addAll(Collection<? extends E> c) {    
        Object[] a = c.toArray();    
        int numNew = a.length;    
        ensureCapacity(size + numNew);  // Increments modCount    
        System.arraycopy(a, 0, elementData, size, numNew);    
        size += numNew;    
        return numNew != 0;    
    }    

    // 從index位置開始,將集合c添加到ArrayList    
    public boolean addAll(int index, Collection<? extends E> c) {    
        if (index > size || index < 0)    
            throw new IndexOutOfBoundsException(    
            "Index: " + index + ", Size: " + size);    

        Object[] a = c.toArray();    
        int numNew = a.length;    
        ensureCapacity(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;    
    }    

    // 刪除fromIndex到toIndex之間的全部元素。    
    protected void removeRange(int fromIndex, int toIndex) {    
    modCount++;    
    int numMoved = size - toIndex;    
        System.arraycopy(elementData, toIndex, elementData, fromIndex,    
                         numMoved);    

    // Let gc do its work    
    int newSize = size - (toIndex-fromIndex);    
    while (size != newSize)    
        elementData[--size] = null;    
    }    

    private void RangeCheck(int index) {    
    if (index >= size)    
        throw new IndexOutOfBoundsException(    
        "Index: "+index+", Size: "+size);    
    }    


    // 克隆函數(shù)    
    public Object clone() {    
        try {    
            ArrayList<E> v = (ArrayList<E>) super.clone();    
            // 將當(dāng)前ArrayList的全部元素拷貝到v中    
            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();    
        }    
    }    


    // java.io.Serializable的寫入函數(shù)    
    // 將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();    

        // 寫入“數(shù)組的容量”    
        s.writeInt(elementData.length);    

    // 寫入“數(shù)組的每一個(gè)元素”    
    for (int i=0; i<size; i++)    
            s.writeObject(elementData[i]);    

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

    }    


    // java.io.Serializable的讀取函數(shù):根據(jù)寫入方式讀出    
    // 先將ArrayList的“容量”讀出,然后將“所有的元素值”讀出    
    private void readObject(java.io.ObjectInputStream s)    
        throws java.io.IOException, ClassNotFoundException {    
        // Read in size, and any hidden stuff    
        s.defaultReadObject();    

        // 從輸入流中讀取ArrayList的“容量”    
        int arrayLength = s.readInt();    
        Object[] a = elementData = new Object[arrayLength];    

        // 從輸入流中將“所有的元素值”讀出    
        for (int i=0; i<size; i++)    
            a[i] = s.readObject();    
    }    
}  

總結(jié)

  • ArrayList有三個(gè)不同的構(gòu)造方法,無參構(gòu)造方法的容量默認(rèn)為10,帶指定容量的構(gòu)造方法,帶Collection參數(shù)的構(gòu)造方法將Collection轉(zhuǎn)化為數(shù)組賦值給ArrayList中的實(shí)現(xiàn)數(shù)組。

  • ensureCapacity方法,每次添加元素時(shí)都要調(diào)用該方法來確保足夠的容量,當(dāng)容量不足以容納當(dāng)前的元素個(gè)數(shù)時(shí),就設(shè)置新的容量為舊的容量的1.5倍加1,如果設(shè)置后的新容量還不夠,則直接新容量設(shè)置為傳入的參數(shù)(也就是所需的容量),然后用Arrays.copyof()方法將元素拷貝到新的數(shù)組。

  • ArrayList在容量不足時(shí)添加元素,都會(huì)進(jìn)行數(shù)組的拷貝,所以會(huì)非常耗時(shí),因此建議在事先知道元素個(gè)數(shù)的情況下使用ArrayList,否則建議使用LinkedList。

  • ArrayList基于數(shù)組實(shí)現(xiàn),可通過下標(biāo)直接查找,所以查找效率高,添加刪除元素時(shí)要移動(dòng)大量元素,所以添加刪除元素效率低。

  • ArrayList允許元素為null。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

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

  • 每個(gè) ArrayList 實(shí)例都有一個(gè)容量,該容量是指用來存儲(chǔ)列表元素的數(shù)組的大小。它總是至少等于列表的大小。隨著...
    Mervyn_2014閱讀 256評論 0 0
  • ArrayList是在Java中最常用的集合之一,其本質(zhì)上可以當(dāng)做是一個(gè)可擴(kuò)容的數(shù)組,可以添加重復(fù)的數(shù)據(jù),也支持隨...
    ShawnIsACoder閱讀 625評論 4 7
  • ArrayList 原文見:Java 容器源碼分析之 ArrayList 概述 ArrayList是使用頻率最高的...
    Leocat閱讀 274評論 0 0
  • 概述 在分析ArrayList源碼之前,先看一下ArrayList在數(shù)據(jù)結(jié)構(gòu)中的位置,常見的數(shù)據(jù)結(jié)構(gòu)按照邏輯結(jié)構(gòu)跟...
    wustor閱讀 619評論 4 2
  • ArrayList是基于數(shù)組實(shí)現(xiàn)的,是一個(gè)動(dòng)態(tài)數(shù)組,其容量能自動(dòng)增長,類似于C語言中的動(dòng)態(tài)申請內(nèi)存,動(dòng)態(tài)增長內(nèi)存。...
    小帝Ele閱讀 292評論 0 2

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