JDK8源碼解析之ArrayList

ArrayList簡(jiǎn)介

ArrayList,從名字上就可以看出來,它是一個(gè)數(shù)組隊(duì)列,相當(dāng)于動(dòng)態(tài)數(shù)組,可以存儲(chǔ)為null的值。除了不支持并發(fā)訪問,完全等同于Vector。

ArrayList不是線程安全的,只能用在單線程環(huán)境下,多線程環(huán)境下可以考慮用Collections.synchronizedList(List l)函數(shù)返回一個(gè)線程安全的ArrayList類,也可以使用concurrent并發(fā)包下的CopyOnWriteArrayList類。

通常我們說,實(shí)現(xiàn)了什么接口,就相當(dāng)于擁有了什么能力,下面看一下它實(shí)現(xiàn)的接口:

  • 繼承自AbstractList,實(shí)現(xiàn)了List:定義了列表必須實(shí)現(xiàn)的方法
  • RandomAccess:提供隨機(jī)快速訪問的能力
    • ArrayList可以以O(shè)(1)的時(shí)間復(fù)雜度去根據(jù)下標(biāo)訪問元素
  • Cloneable:可以調(diào)用Object.clone()方法返回該對(duì)象的淺拷貝
  • java.io.Serializable:支持序列化,能夠通過序列化傳輸

構(gòu)造方法

    //默認(rèn)初始容量
    private static final int DEFAULT_CAPACITY = 10;
    //所有空實(shí)例共享的空數(shù)組實(shí)例
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    private static final Object[] EMPTY_ELEMENTDATA = {};
    //存儲(chǔ)ArrayList元素的數(shù)組
    transient Object[] elementData;
    //ArrayList中實(shí)際數(shù)據(jù)的數(shù)量
    private int size;

    //初始化時(shí),如果帶容量,使用此構(gòu)造函數(shù)
    public ArrayList(int initialCapacity){
        if (initialCapacity > 0){
            this.elementData = new Object[initialCapacity];
        }else if(initialCapacity == 0){
            this.elementData = EMPTY_ELEMENTDATA;
        }else{
            throw new IllegalArgumentException("Illegal Capacity " + initialCapacity);
        }
    }
    //默認(rèn)的構(gòu)造方法
    public ArrayList(){
        //只是簡(jiǎn)單的將空數(shù)組賦值給了elementData
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    //利用別的集合類來構(gòu)造ArrayList的構(gòu)造函數(shù)
    public ArrayList(Collection<? extends E> c){
        elementData = c.toArray();
        size = elementData.length;
        if (size != 0){
            //c.toArray might (incorrectly) not return Object[] (see 6260652)
            //返回的如果不是Object[]將調(diào)用Arrays.copyOf方法將其轉(zhuǎn)為Object[]
            if (elementData.getClass() != Object[].class){
                elementData = Arrays.copyOf(elementData, size, Object[].class);
            }
        }else{
            this.elementData = EMPTY_ELEMENTDATA;
        }        
    }

介紹一個(gè)方法:Arrays.copyOf(elementData, size, Object[].class),就是根據(jù)class的類型來決定是new 還是反射去構(gòu)造一個(gè)泛型數(shù)組,同時(shí)利用native函數(shù),批量賦值元素至新數(shù)組中。 如下:

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        //根據(jù)class的類型來決定是new 還是反射去構(gòu)造一個(gè)泛型數(shù)組
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        //利用native函數(shù),批量賦值元素至新數(shù)組中。
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

常用API

目前解析中包含的API

  • public int size()
  • public boolean isEmpty()
  • public boolean contains(Object o)
  • public int indexOf(Object o)
  • public int lastIndexOf(Object o)
  • public Object clone()
  • public Object[] toArray()
  • public E get(int index)
  • public E set(int index, E element)
  • public boolean add(E e)
  • public void add(int index, E element)
  • public E remove(int index)
  • public boolean remove(Object o)
  • public void clear()
  • public boolean addAll(Collection<? extends E> c)
  • public boolean addAll(int index, Collection<? extends E> c)
  • public boolean removeAll(Collection<?> c)
  • public boolean retainAll(Collection<?> c)

具體方法的功能和實(shí)現(xiàn)去解析里看就好了,這里不再重復(fù)了。
這是解析的一部分,后面的待補(bǔ)充
總結(jié):
============

  • 因其底層數(shù)據(jù)結(jié)構(gòu)是數(shù)組,所以可想而知,它是占據(jù)一塊連續(xù)的內(nèi)存空間(容量就是數(shù)組的length),所以它也有數(shù)組的缺點(diǎn),空間效率不高。
  • 由于數(shù)組的內(nèi)存連續(xù),可以根據(jù)下標(biāo)以O(shè)1的時(shí)間讀寫(改查)元素,因此時(shí)間效率很高
  • 當(dāng)集合中的元素超出這個(gè)容量,便會(huì)進(jìn)行擴(kuò)容操作。擴(kuò)容操作也是ArrayList 的一個(gè)性能消耗比較大的地方,所以若我們可以提前預(yù)知數(shù)據(jù)的規(guī)模,應(yīng)該通過public ArrayList(int initialCapacity) {}構(gòu)造方法,指定集合的大小,去構(gòu)建ArrayList實(shí)例,以減少擴(kuò)容次數(shù),提高效率
  • 或者在需要擴(kuò)容的時(shí)候,手動(dòng)調(diào)用public void ensureCapacity(int minCapacity) {}方法擴(kuò)容。 不過該方法是ArrayList的API,不是List接口里的,所以使用時(shí)需要強(qiáng)轉(zhuǎn): ((ArrayList)list).ensureCapacity(30);
  • 增刪改查中, 增導(dǎo)致擴(kuò)容,則會(huì)修改modCount,刪一定會(huì)修改改和查一定不會(huì)修改modCount。

源碼

package test;

import java.util.*;

/**
 * Created by 11981 on 2017/10/10.
 */
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    //序列版本號(hào)
    private static final long serialVersionUID = 8683452581122892189L;
    //默認(rèn)初始容量
    private static final int DEFAULT_CAPACITY = 10;
    //所有空實(shí)例共享的空數(shù)組實(shí)例
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    private static final Object[] EMPTY_ELEMENTDATA = {};
    //存儲(chǔ)ArrayList元素的數(shù)組
    transient Object[] elementData;
    //ArrayList中實(shí)際數(shù)據(jù)的數(shù)量
    private int size;

    //初始化時(shí),如果帶容量,使用此構(gòu)造函數(shù)
    public ArrayList(int initialCapacity){

        if (initialCapacity > 0){
            this.elementData = new Object[initialCapacity];
        }else if(initialCapacity == 0){
            this.elementData = EMPTY_ELEMENTDATA;
        }else{

            throw new IllegalArgumentException("Illegal Capacity " + initialCapacity);
        }
    }
    //默認(rèn)的構(gòu)造方法
    public ArrayList(){
        //只是簡(jiǎn)單的將空數(shù)組賦值給了elementData
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    //利用別的集合類來構(gòu)造ArrayList的構(gòu)造函數(shù)
    public ArrayList(Collection<? extends E> c){
        elementData = c.toArray();
        size = elementData.length;
        if (size != 0){
            //c.toArray might (incorrectly) not return Object[] (see 6260652)
            //返回的如果不是Object[]將調(diào)用Arrays.copyOf方法將其轉(zhuǎn)為Object[]
            if (elementData.getClass() != Object[].class){
                elementData = Arrays.copyOf(elementData, size, Object[].class);
            }
        }else{
            this.elementData = EMPTY_ELEMENTDATA;
        }

    }


    /**將ArrayList實(shí)例的容量裁剪到list當(dāng)前大小Size
     * 應(yīng)用程序使用該操作降低ArrayList實(shí)例占用的存儲(chǔ)
     * 因?yàn)榍蹇盏纫恍┎僮髦桓淖儏?shù)而沒有釋放空間
     */

    public void trimToSize(){
        //來自AbstractList,用于記錄操作的次數(shù)
        modCount++;
        int oldCapacity = elementData.length;
        if (size < oldCapacity){
            elementData = Arrays.copyOf(elementData, size);
        }
    }

    /**
     * 提升ArrayList實(shí)例的容量,確保它可以保存至少minCapacity的元素
     */
    public void ensureCapacity(int minCapacity){
        //如果數(shù)組當(dāng)前為空,則添加元素時(shí)最小增長(zhǎng)容量為DEFAULT_CAPACITY
        //否則,增長(zhǎng)容量大于零即可
        int midExpend = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) ? 0 : DEFAULT_CAPACITY;
        if (minCapacity > midExpend){
            ensureExplicitCapacity(minCapacity);
        }
    }

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

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity){
        modCount++;//list結(jié)構(gòu)被改變的次數(shù)

        //當(dāng)目標(biāo)容量大于當(dāng)前容量時(shí)才增長(zhǎng)
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    //數(shù)組可分配的最大容量,有些虛擬機(jī)中會(huì)給數(shù)組保留頭部,嘗試分配更大的數(shù)組會(huì)導(dǎo)致內(nèi)存溢出
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    //提升容量,確保它可以存儲(chǔ)指定參數(shù)個(gè)元素
    private void grow(int minCapacity){
        int oldCapacity = elementData.length;
        //增加原來容量的一般(右移一位相當(dāng)于除以2)
        //使用移位運(yùn)算符效率更高
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - oldCapacity < 0)
            newCapacity = oldCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        //返回一個(gè)內(nèi)容為原數(shù)組元素,大小為新容量的數(shù)組賦值給elementData
        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;
    }

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

    /**
     * 若列表中包含該元素時(shí)就返回true
     * @param o
     * @return
     */
    public boolean contains(Object o){
        return indexOf(o) >= 0;
    }

    /**
     * 通過遍歷elementData數(shù)組來判斷對(duì)象是否存在于list中,若存在,返回首次出現(xiàn)的index(0, size-1)
     * 若不存在,返回-1
     * 所以contains方法可以通過indexOf(Object)方法的返回值來判斷對(duì)象是否被包含在list中
     * @param o
     * @return
     */
    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 (elementData[i].equals(o))
                    return i;
        }
        return -1;
    }

    /**
     * 返回的是傳入對(duì)象在elementData數(shù)組中最后出現(xiàn)的index值,沒有則是-1
     * @param o
     * @return
     */
    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 (elementData[i].equals(o))
                    return i;
        }
        return -1;
    }

    /**
     * 返回ArrayList實(shí)例的淺表副本
     * @return
     */
    public Object clone(){
        try{
            //調(diào)用父類的clone方法返回一個(gè)對(duì)象的副本
            ArrayList<?> v = (ArrayList<?>) super.clone();
            //將返回對(duì)象的elementData數(shù)組的內(nèi)容賦值為原對(duì)象elementData數(shù)組的內(nèi)容
            v.elementData = Arrays.copyOf(elementData, size);
            //將副本的modCount設(shè)置為0
            v.modCount = 0;
            return v;

        }catch (CloneNotSupportedException e){
            throw new InternalError(e);
        }
    }
    //返回一個(gè)包含列表中所有元素的數(shù)組
    //返回的數(shù)組是一個(gè)安全的數(shù)組,即沒有列表中的引用,是一個(gè)全新申請(qǐng)的數(shù)組
    public Object[] toArray(){
        return Arrays.copyOf(elementData, size);
    }

    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a){
        //如果傳入的數(shù)組長(zhǎng)度小于size,返回一個(gè)新的數(shù)組,大小為size,類型與原來相同
        if (a.length < size)
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        //否則,將elementData復(fù)制到傳入數(shù)組,并返回傳入數(shù)組
        System.arraycopy(elementData, 0, a, 0, size);
        //若傳入數(shù)組長(zhǎng)度大于size,把返回?cái)?shù)組的第size個(gè)元素置為空
        if (a.length > size)
            a[size] = null;
        return a;

    }

    E elementData(int index){
        return (E) elementData[index];
    }

    /**
     * 返回指定位置的元素
     * @param index
     * @return
     */
    public E get(int index){
        //范圍檢查
        rangeCheck(index);
        return elementData(index);
    }

    /**
     * 將列表中指定位置的元素替換為指定元素,并返回原先位置的元素
     * @param index
     * @param element
     * @return
     */
    public E set(int index, E element){
        rangeCheck(index);

        //簡(jiǎn)單的替換步驟
        //E oldValue = (E)elementData[index];
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;

    }

    //在列表尾部添加一個(gè)元素,容量的擴(kuò)展將導(dǎo)致數(shù)組元素的復(fù)制,多次擴(kuò)展將執(zhí)行多次整個(gè)數(shù)組內(nèi)容的復(fù)制
    //若能提前判斷l(xiāng)ist的長(zhǎng)度,調(diào)用ensureCapacity調(diào)整容量,將有效的提高運(yùn)行速度
    public boolean add(E e){
        ensureCapacityIntenal(size + 1);//Increments modCount
        elementData[size++] = e;
        return true;
    }

    /**
     * 在指定位置插入元素,當(dāng)前位置原元素及所有后繼元素向右移動(dòng)一個(gè)位置
     * @param index
     * @param element
     */

    public void add(int index, E element){
        //判斷指定位置index是否超出elementData的界限
        rangeCheckForAdd(index);
        ensureCapacityIntenal(size + 1);
        //調(diào)用System.arrayCopy將elementData從index開始到size結(jié)束的size-index(長(zhǎng)度)個(gè)元素復(fù)制到index+1至size+1的位置
        //即將從index開始的元素都往后移動(dòng)一個(gè)位置,然后將index位置的值指向element。
        System.arraycopy(elementData, index, elementData, index+1, size-index);
        elementData[index] = element;
        size++;
    }

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

    /**
     * 刪除指定位置的元素,將后繼元素向前移動(dòng)一個(gè)位置
     * @param index
     * @return
     */
    public E remove(int index){
        rangeCheck(index);
        modCount++;
        //保留要被移除的元素
        E oldValue = elementData(index);
        int numMoved = size - index - 1;
        if (numMoved > 0)
            //將移除位置之后的元素向前挪動(dòng)一個(gè)位置
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        //將list末尾元素置null
        elementData[--size] = null;
        //返回被移除的元素
        return oldValue;
    }

    /**
     * 刪除首次出現(xiàn)在列表中的元素,如果不包含該元素,則不作變化
     * @param o
     * @return
     */
    public boolean remove(Object o){
        if (o == null){
            for (int i = 0; i < size; i++){
                if (elementData[i] == null)
                {
                    fastRemove(i);
                    return true;
                }
            }
        }else{
            for (int i = 0; i < size; i++){
                if (o.equals(elementData[i])){
                    fastRemove(i);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 跳過邊界檢查也不刪除值的刪除函數(shù)
     * @param index
     */
    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
    }

    /**
     * 清空列表中所有元素,操作后列表為空
     */
    public void clear(){
        modCount++;
        //clear to let GC do its work
        for (int i = 0; i < size; i++){
            elementData[i] = null;
        }
        size = 0;
    }

    /**
     * 將指定集合中的所有元素都添加到列表末尾,以其迭代器返回的順序添加
     * !!該操作在多線程情況下行為未定義,需要外部同步
     * @param c
     * @return
     */
    public boolean addAll(Collection<? extends E> c){
        //先集合C轉(zhuǎn)換為數(shù)組
        Object[] a = c.toArray();
        //得到數(shù)組的長(zhǎng)度
        int numNew = a.length;
        //將該數(shù)組復(fù)制到列表的尾部
        if (numNew > 0)
            System.arraycopy(a, 0, elementData, size, numNew);
        //size實(shí)時(shí)更新
        size += numNew;
        //只要集合c的大小不為空,即轉(zhuǎn)換后數(shù)組長(zhǎng)度不為0則返回true
        return numNew != 0;
    }

    /**
     * 將指定集合c中所有元素添加到以index開頭的位置中,將當(dāng)前元素及所有
     * 后繼元素向后移動(dòng),新元素的順序以迭代器返回的順序?yàn)闇?zhǔn)
     * @param index
     * @param c
     * @return
     */
    public boolean addAll(int index, Collection<? extends E> c){
        //檢查是否越界
        rangeCheckForAdd(index);
        Object[] a = c.toArray();
        int numNew = a.length;
        //Increments modCount
        ensureCapacityIntenal(size + numNew);
        int numMoved = size - index;
        //先將index開始的元素向后移動(dòng)numNew(c轉(zhuǎn)換為數(shù)組后的長(zhǎng)度)個(gè)位置(也是一個(gè)復(fù)制的過程)
        //也是為后面的插入留下空間
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
        //將數(shù)組內(nèi)容復(fù)制到elementData的index到index+numNew
        System.arraycopy(a, 0, elementData, index, numNew);
        //更新size
        size += numNew;
        return numNew != 0;
    }

    protected void removeRange(int fromIndex, int toIndex){
        modCount++;
        int numMoved = size - toIndex;
        if (numMoved > 0)
            System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved);
        //移除元素后,列表應(yīng)該的容量
        int newSize = size - (toIndex - fromIndex);
        //將toIndex后的元素置為null,讓垃圾收集器進(jìn)行回收工作
        for (int i = newSize; i < size; i++)
            elementData[i] = null;

        size = newSize;
    }

    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;
    }

    public boolean removeAll(Collection<?> c){
        //當(dāng)傳入的參數(shù)不為null時(shí),返回參數(shù)本身,反之拋出NullPointException異常
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

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

    /**
     * ???
     * 批量刪除
     * complement為false,則為刪除列表中出現(xiàn)在集合c中的元素
     * complement為true,則為刪除列表中未出現(xiàn)在集合c中的元素
     */
    private boolean batchRemove(Collection<?> c, boolean complement){
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;//w代表批量刪除后,還剩多少元素
        boolean modified = false;
        try{
            //高效保存兩個(gè)結(jié)合公有元素的算法
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        }finally {
            if (r != size){
                System.arraycopy(elementData, r, elementData, w, size-r);
                w += size - r;
            }
            if (w != size){
                for (int i = w; i < size; i++){
                    elementData[i] = null;
                }
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }
}

Reference

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

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

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