02霍骄、ArrayList源碼分析

ArrayList是基于數(shù)組實現(xiàn)的,是一個動態(tài)數(shù)組淡溯,其容量能自動增長读整,類似于C語言中的動態(tài)申請內(nèi)存,動態(tài)增長內(nèi)存咱娶。

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

ArrayList實現(xiàn)了Serializable接口,因此它支持序列化琼了,能夠通過序列化傳輸逻锐,實現(xiàn)了RandomAccess接口,支持快速隨機(jī)訪問雕薪,實際上就是通過下標(biāo)序號進(jìn)行快速訪問昧诱,實現(xiàn)了Cloneable接口,能被克隆所袁。

image

ArrayList源碼剖析

ArrayList的源碼如下(加入了比較詳細(xì)的注釋):

package java.util;  

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

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

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

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

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

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

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

    // 確定ArrarList的容量懦窘。  
    // 若ArrayList的容量不足以容納當(dāng)前的全部元素,設(shè)置 
    // 新的容量=“(原始容量x3)/2 + 1”  
    public void ensureCapacity(int minCapacity) {  
        // 將“修改統(tǒng)計數(shù)”+1勺拣,該變量主要是用來實現(xiàn)fail-fast機(jī)制的  
        modCount++;  
        int oldCapacity = elementData.length;  
        // 若當(dāng)前容量不足以容納當(dāng)前的元素個數(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);  
        }  
    }  

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

    // 返回ArrayList的實際大小  
    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;  
        }  

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

    // 反向查找(從數(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ù)組
    publicT[] toArray(T[] a) {  
        // 若數(shù)組a的大小 < ArrayList的元素個數(shù)愤惰;  
        // 則新建一個T[]數(shù)組苇经,數(shù)組大小是“ArrayList的元素個數(shù)”,
        // 并將“ArrayList”全部拷貝到新數(shù)組中  
        if (a.length < size)  
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());  

        // 若數(shù)組a的大小 >= ArrayList的元素個數(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添加到ArrayList中  
    public boolean add(E e) {  
        ensureCapacity(size + 1);  // Increments modCount!!  
        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];  

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

    // 刪除元素  
    public boolean remove(Object o) {  
        if (o == null) {  
            for (int index = 0; index < size; index++)  
            if (elementData[index] == null) {  
                fastRemove(index);  
            return true;  
            }  
        } else {  
            // 便利ArrayList蜘澜,找到“元素o”,則刪除响疚,并返回true鄙信。  
            for (int index = 0; index < size; index++)  
            if (o.equals(elementData[index])) {  
                fastRemove(index);  
            return true;  
            }  
        }  
        return false;  
    }  

    // 清空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 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 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 {  
            ArrayListv = (ArrayList) 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ù)組的每一個元素”  
    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é)

關(guān)于ArrayList的源碼鸦采,給出幾點比較重要的總結(jié):

1. 注意其三個不同的構(gòu)造方法。無參構(gòu)造方法構(gòu)造的ArrayList的容量默認(rèn)為10咕幻,帶有Collection參數(shù)的構(gòu)造方法渔伯,將Collection轉(zhuǎn)化為數(shù)組賦給ArrayList的實現(xiàn)數(shù)組elementData。

2. 注意擴(kuò)充容量的方法ensureCapacity肄程。ArrayList在每次增加元素(可能是1個锣吼,也可能是一組)時,都要調(diào)用該方法來確保足夠的容量绷耍。當(dāng)容量不足以容納當(dāng)前的元素個數(shù)時,就設(shè)置新的容量為舊的容量的1.5倍加1鲜侥,如果設(shè)置后的新容量還不夠褂始,則直接新容量設(shè)置為傳入的參數(shù)(也就是所需的容量),而后用Arrays.copyof()方法將元素拷貝到新的數(shù)組(詳見下面的第3點)描函。

從中可以看出崎苗,當(dāng)容量不夠時狐粱,每次增加元素,都要將原來的元素拷貝到一個新的數(shù)組中胆数,非常之耗時肌蜻,也因此建議在事先能確定元素數(shù)量的情況下,才使用ArrayList必尼,否則建議使用LinkedList蒋搜。

image

3. ArrayList的實現(xiàn)中大量地調(diào)用了Arrays.copyof()和System.arraycopy()方法。我們有必要對這兩個方法的實現(xiàn)做下深入的了解判莉。

  • Arrays.copyof() 方法:它有很多個重載的方法豆挽,但實現(xiàn)思路都是一樣的,我們來看泛型版本的源碼:
public staticT[] copyOf(T[] original, int newLength) {    
    return (T[]) copyOf(original, newLength, original.getClass());
}

很明顯調(diào)用了另一個copyof方法券盅,該方法有三個參數(shù)帮哈,最后一個參數(shù)指明要轉(zhuǎn) 換的數(shù)據(jù)的類型,其源碼如下:

public staticT[] copyOf(U[] original, int newLength, Class newType) {
    T[] copy = ((Object)newType == (Object)Object[].class)
        ? (T[]) new Object[newLength]
        : (T[]) Array.newInstance(newType.getComponentType(), newLength);
    System.arraycopy(original, 0, copy, 0,                  
       Math.min(original.length, newLength));    return copy;
}

這里可以很明顯地看出锰镀,該方法實際上是在其內(nèi)部又創(chuàng)建了一個長度為 newlength的數(shù)組娘侍,調(diào)用System.arraycopy()方法,將原來數(shù)組中的元素復(fù)制到了新的數(shù)組中泳炉。

  • System.arraycopy() 方法:該方法被標(biāo)記了native憾筏,調(diào)用了系統(tǒng)的C/C++代碼,在JDK中是看不到的胡桃,但在openJDK中可以看到其源碼踩叭。該函數(shù)實際上最終調(diào)用了C語言的memmove()函數(shù),因此它可以保證同一個數(shù)組內(nèi)元素的正確復(fù)制和移動翠胰,比一般的復(fù)制方法的實現(xiàn)效率要高很多容贝,很適合用來批量處理數(shù)組。Java強(qiáng)烈推薦在復(fù)制大量數(shù)組元素時用該方法之景,以取得更高的效率斤富。

4. 注意ArrayList的兩個轉(zhuǎn)化為靜態(tài)數(shù)組的toArray方法。

  • 第一個锻狗,Object[] toArray()方法满力。該方法有可能會拋出java.lang.ClassCastException異常,如果直接用向下轉(zhuǎn)型的方法轻纪,將整個ArrayList集合轉(zhuǎn)變?yōu)橹付愋偷腁rray數(shù)組油额,便會拋出該異常,而如果轉(zhuǎn)化為Array數(shù)組時不向下轉(zhuǎn)型刻帚,而是將每個元素向下轉(zhuǎn)型潦嘶,則不會拋出該異常,顯然對數(shù)組中的元素一個個進(jìn)行向下轉(zhuǎn)型崇众,效率不高掂僵,且不太方便航厚。

  • 第二個, T[] toArray(T[] a)方法锰蓬。該方法可以直接將ArrayList轉(zhuǎn)換得到的Array進(jìn)行整體向下轉(zhuǎn)型(轉(zhuǎn)型其實是在該方法的源碼中實現(xiàn)的)幔睬,且從該方法的源碼中可以看出,參數(shù)a的大小不足時芹扭,內(nèi)部會調(diào)用Arrays.copyOf方法麻顶,該方法內(nèi)部創(chuàng)建一個新的數(shù)組返回,因此對該方法的常用形式如下:

public static Integer[] vectorToArray2(ArrayListv) {  
    Integer[] newText = (Integer[])v.toArray(new Integer[0]);  
    return newText;  
}

5. ArrayList基于數(shù)組實現(xiàn)冯勉,可以通過下標(biāo)索引直接查找到指定位置的元素澈蚌,因此查找效率高,但每次插入或刪除元素灼狰,就要大量地移動元素宛瞄,插入刪除元素的效率低。

6. 在查找給定元素索引值等的方法中交胚,源碼都將該元素的值分為null和不為null兩種情況處理份汗,ArrayList中允許元素為null。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蝴簇,一起剝皮案震驚了整個濱河市杯活,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌熬词,老刑警劉巖旁钧,帶你破解...
    沈念sama閱讀 221,198評論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異互拾,居然都是意外死亡歪今,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評論 3 398
  • 文/潘曉璐 我一進(jìn)店門颜矿,熙熙樓的掌柜王于貴愁眉苦臉地迎上來寄猩,“玉大人,你說我怎么就攤上這事骑疆√锲” “怎么了?”我有些...
    開封第一講書人閱讀 167,643評論 0 360
  • 文/不壞的土叔 我叫張陵箍铭,是天一觀的道長泊柬。 經(jīng)常有香客問我,道長诈火,這世上最難降的妖魔是什么兽赁? 我笑而不...
    開封第一講書人閱讀 59,495評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上闸氮,老公的妹妹穿的比我還像新娘。我一直安慰自己教沾,他們只是感情好蒲跨,可當(dāng)我...
    茶點故事閱讀 68,502評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著授翻,像睡著了一般或悲。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上堪唐,一...
    開封第一講書人閱讀 52,156評論 1 308
  • 那天巡语,我揣著相機(jī)與錄音,去河邊找鬼淮菠。 笑死男公,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的合陵。 我是一名探鬼主播枢赔,決...
    沈念sama閱讀 40,743評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼拥知!你這毒婦竟也來了踏拜?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,659評論 0 276
  • 序言:老撾萬榮一對情侶失蹤低剔,失蹤者是張志新(化名)和其女友劉穎速梗,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體襟齿,經(jīng)...
    沈念sama閱讀 46,200評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡姻锁,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,282評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了蕊唐。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片屋摔。...
    茶點故事閱讀 40,424評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖替梨,靈堂內(nèi)的尸體忽然破棺而出钓试,到底是詐尸還是另有隱情,我是刑警寧澤副瀑,帶...
    沈念sama閱讀 36,107評論 5 349
  • 正文 年R本政府宣布弓熏,位于F島的核電站,受9級特大地震影響糠睡,放射性物質(zhì)發(fā)生泄漏挽鞠。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,789評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望信认。 院中可真熱鬧材义,春花似錦、人聲如沸嫁赏。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,264評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽潦蝇。三九已至款熬,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間攘乒,已是汗流浹背贤牛。 一陣腳步聲響...
    開封第一講書人閱讀 33,390評論 1 271
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留则酝,地道東北人殉簸。 一個月前我還...
    沈念sama閱讀 48,798評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像沽讹,于是被迫代替她去往敵國和親喂链。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,435評論 2 359