Java中ArrayList源碼淺析

ArrayList基本使用

public class ArrayListTest {

    public static void main(String[] args) {
        List list = new ArrayList<>();
        list.add("5");
        System.out.println(list.get(0));
    }
}

ArrayList繼承層次

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

基本字段

    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * Default initial capacity.
     */
    //默認(rèn)的初始化容量
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     */
     //空數(shù)組,會在構(gòu)造函數(shù)中給予0參數(shù)的情況下,賦值給elementData
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     */
    //在一個個元素加入進(jìn)來的時候,會自動擴(kuò)展成為DEFAULTCAPACITY
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    //真正的數(shù)組的引用
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    //添加的元素數(shù)量
    private int size;

    /**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     */
     //是因為有header words?才導(dǎo)致要Integer的最大值減8
     //其實這個變量只在后面使用一次,比較了之后,然后還是按照MAX_VALUE來擴(kuò)容了...為啥
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

構(gòu)造函數(shù)

    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    //帶有初始化容量的構(gòu)造函數(shù)
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            //初始化一個initialCapacity大小的Object數(shù)組
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            //若初始化為0,則使用默認(rèn)的空數(shù)組賦值
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            //若為負(fù)數(shù),拋出非法參數(shù)異常
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    //最基本的構(gòu)造函數(shù)
    public ArrayList() {
        //注意這里被賦值為DEFAULTCAPACITY_EMPTY_ELEMENTDATA
        //而不是EMPTY_ELEMENTDATA,表示的意思就是當(dāng)add的時候
        //會默認(rèn)擴(kuò)容為DEFAULT_CAPACITY
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

add操作

    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        //添加元素的時候,調(diào)用內(nèi)部確保容量的方法
       //為什么是內(nèi)部呢?因為還有一個共有的ensureCapacity方法
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //因為本身是一個數(shù)組,所以在下一個數(shù)組索引位置添加上元素
        elementData[size++] = e;
        return true;
    }
    private void ensureCapacityInternal(int minCapacity) {
        //如果elementDate等于DEFAULTCAPACITY_EMPTY_ELEMENTDATA
        //表示第一次擴(kuò)容時,起碼要擴(kuò)容至DEFAULT_CAPACITY
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            //取DEFAULT_CAPACITY=10和minCapacity(可以在初始化函數(shù)中初始化)的最大值
            //也就是說若調(diào)用默認(rèn)構(gòu)造函數(shù),第一次會起碼擴(kuò)展為10的大小
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        //確保顯示的容量
        ensureExplicitCapacity(minCapacity);
    }

其實ensureCapacityInternal一個任務(wù)是算出不論是第一次添加導(dǎo)致的擴(kuò)容還是后面添加導(dǎo)致的擴(kuò)容的最小的容量值。然后將這個最小擴(kuò)容值傳遞給ensureExplicitCapacity,由ensureExplicitCapacity實現(xiàn)擴(kuò)容。

    private void ensureExplicitCapacity(int minCapacity) {
        //用于迭代器的fail fast機(jī)制
        modCount++;

        // overflow-conscious code
       //如果最小容量大于數(shù)組的長度,那么擴(kuò)容。
       //否則,則不擴(kuò)容。
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    /**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     *
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        //新的容量為舊的容量的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //如果擴(kuò)了1.5倍之后,還是小,那么以最小的容量進(jìn)行擴(kuò)容
        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擴(kuò)展為newCapacity大小,使用復(fù)制數(shù)組的方式
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
    private static int hugeCapacity(int minCapacity) {
        //如果minCapacity小于0(而minCapacity是由某數(shù)+1得到)
        //其實也剛開始想錯了,minCapacity也有可能是addAll()調(diào)用導(dǎo)致的
        //反正minCapacity是一個需要保證的最小的容量值,不需要去理解
        //其他函數(shù)是如何調(diào)用的
        //所以minCapacity是由于Integer溢出的
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
       //這里表示將最大容量擴(kuò)展為Integer.MAX_VALUE,那么MAX_ARRAY_SIZE還有什么意義呢?
        //這里minCapacity沒有溢出說明是小于MAX_ARRAY_SIZE,但是分為兩種情況,如果小于MAX_ARRAY_SIZE
       //那么就直接擴(kuò)容為MAX_ARRAY_SIZE
       //否則比如說是MAX_VALUE-2,那么最多擴(kuò)容為MAX_VALUE
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

get操作

    /**
     * Returns the element at the specified position in this list.
     *
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        //判斷是否越界
        rangeCheck(index);
        //返回數(shù)組的值
        return elementData(index);
    }
    /**
     * Checks if the given index is in range.  If not, throws an appropriate
     * runtime exception.  This method does *not* check if the index is
     * negative: It is always used immediately prior to an array access,
     * which throws an ArrayIndexOutOfBoundsException if index is negative.
     */
    private void rangeCheck(int index) {
        if (index >= size)
            //如果下標(biāo)大于元素的數(shù)量,那么拋出異常
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

remove操作

    /**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     *
     * @param index the index of the element to be removed
     * @return the element that was removed from the list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        rangeCheck(index);
        //add和remove都需要讓modCount加一
        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //最大位的引用置為null,讓GC回收
        elementData[--size] = null; // clear to let GC do its work
        //返回刪除的值
        return oldValue;
    }

參考

自己動手系列——實現(xiàn)一個簡單的ArrayList
Arrays.copyof(···)與System.arraycopy(···)區(qū)別
Java提高篇(三四)—–fail-fast機(jī)制
why-the-maximum-array-size-of-arraylist-is-integer-max-value-8---其實并不是按照Integer.MAX_VALUE - 8來進(jìn)行的
Java中ArrayList最大容量為什么是Integer.MAX_VALUE-8?---感覺知乎上面理解的對一些
Why I can't create an array with large size?----還有這個Java里面數(shù)組最大可以開多大

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,106評論 6 542
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,441評論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,211評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,736評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 72,475評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,834評論 1 328
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,829評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,009評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,559評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,306評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,516評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,038評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,728評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,132評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,443評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,249評論 3 399
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 48,484評論 2 379

推薦閱讀更多精彩內(nèi)容