深入分析 ArrayList

基于JDK 1.8.0。

簡(jiǎn)介:

ArrayList 底層是通過(guò)數(shù)組實(shí)現(xiàn)的,相當(dāng)于一個(gè)動(dòng)態(tài)的數(shù)組澳迫。

特點(diǎn):

  • 底層實(shí)現(xiàn):使用數(shù)組實(shí)現(xiàn)葛躏。
  • 線程安全:線程不安全澈段。
  • 擴(kuò)容:可以動(dòng)態(tài)擴(kuò)容。
  • 是否可以存放null:可以存放null
  • 是否有序:
  • 效率:取元素比較快舰攒,時(shí)間復(fù)雜度都是O(1) 败富, 增加刪減元素慢,會(huì)導(dǎo)致元素的移動(dòng)摩窃。
  • 是否可以重復(fù):可以放入重復(fù)的元素兽叮。

源碼分析:

ArrayList 里面最基礎(chǔ)的兩個(gè)屬性 elementData 和 size。elementData 是一個(gè)對(duì)象數(shù)組偶芍,用于存放元素充择。size則是表示實(shí)際ArrayList里面的元素個(gè)數(shù)。

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer.
     */
    private transient Object[] elementData;

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

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

ArrayList有3個(gè)構(gòu)造函數(shù)

  1. 可以從源碼看出匪蟀,傳入一個(gè)整形的初始容量值作為數(shù)組的長(zhǎng)度然后new一個(gè)數(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
     */
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }



2.不傳任何參數(shù),默認(rèn)10為數(shù)組長(zhǎng)度材彪,調(diào)用帶參數(shù)的構(gòu)造函數(shù)來(lái)創(chuàng)建观挎。

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this(10);
    }



3.傳入一個(gè)Collection集合對(duì)象琴儿,然后將集合轉(zhuǎn)換為Object數(shù)組。并設(shè)置size屬性為elementData數(shù)組的長(zhǎng)度嘁捷。

    /**
     * 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();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }



在分析添加方法之前造成,有2個(gè)方法需要了解和分析的。一個(gè)是ensureCapacityInternal()雄嚣,另一個(gè)是grow()晒屎。

ensureCapacityInternal 方法是檢查當(dāng)前對(duì)象數(shù)組的容量能否滿足將要裝的元素的最大長(zhǎng)度。如果不能滿足缓升,則動(dòng)態(tài)擴(kuò)容鼓鲁。擴(kuò)容方法則是grow方法。

 /**
     * Increases the capacity of this <tt>ArrayList</tt> instance, if
     * necessary, to ensure that it can hold at least the number of elements
     * specified by the minimum capacity argument.
     *
     * @param   minCapacity   the desired minimum capacity
     */
    public void ensureCapacity(int minCapacity) {
        if (minCapacity > 0)
            ensureCapacityInternal(minCapacity);
    }

    private void ensureCapacityInternal(int minCapacity) {
        //修改次數(shù)+1
        modCount++;
        // overflow-conscious code
        //如果最小容量大于當(dāng)前數(shù)組的長(zhǎng)度港谊,就擴(kuò)容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

grow() 方法是對(duì)ArrayList的動(dòng)態(tài)擴(kuò)容骇吭。操作是,計(jì)算出新的容量歧寺,創(chuàng)建新的數(shù)組燥狰,然后將舊的數(shù)組元素復(fù)制到新的數(shù)組, 然后使用新的數(shù)組斜筐。

/**
     * 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
        //獲取當(dāng)前的數(shù)組的長(zhǎng)度龙致,即當(dāng)前的容量。
        int oldCapacity = elementData.length;

        //新容量的計(jì)算 = 舊容量 + 舊容量右移1位
        //右移運(yùn)算=對(duì)應(yīng)數(shù)字的二進(jìn)制數(shù)的最右補(bǔ)充1位
        // 相當(dāng)于  十進(jìn)制 / 2奴艾,但不等于净当,例如 1 右移1位=0
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        
        //如果舊容量仍然大于新容量,則新容量=舊容量
        //如果容量的計(jì)算超出了int的取值范圍蕴潦,就會(huì)導(dǎo)致溢出
        //就會(huì)導(dǎo)致出現(xiàn)舊容量大于新容量的情況
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;

        //如果新容量大于最大數(shù)組大小的話像啼,就調(diào)用獲取巨大容量方法。
        //hugeCapacity 返回的最大值其實(shí)也只是 Integer.MAX_VALUE .
        //那么就是說(shuō)潭苞,ArrayList的最大容量是 Integer.MAX_VALUE 
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);

        // minCapacity is usually close to size, so this is a win:
        //最后調(diào)用copyOf方法創(chuàng)建新的數(shù)組忽冻,并且將舊數(shù)組的元素復(fù)制到新數(shù)組
        elementData = Arrays.copyOf(elementData, newCapacity);

    }



添加元素

添加元素方法有兩種,一種是添加單個(gè)元素此疹,一種是添加一個(gè)集合僧诚。添加單個(gè)元素使用add()方法,add()方法有1個(gè)重載蝗碎。 添加集合使用addAll()方法湖笨,addAll()方法也有1個(gè)重載。


  1. 添加一個(gè)元素蹦骑,不指定位置慈省。雖然是直接將元素添加到數(shù)組的最尾端,不用移動(dòng)數(shù)組眠菇。但是我覺(jué)得效率還是不太好边败,因?yàn)槿绻麛?shù)組容量不夠的時(shí)候袱衷,擴(kuò)容的時(shí)候還是要將數(shù)組復(fù)制一遍。
 /**
     * 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) {
        //檢查容量是否足夠笑窜,如果不足致燥,則會(huì)擴(kuò)容。
        ensureCapacityInternal(size + 1);  // Increments modCount!!

        //將新的元素放到數(shù)組的尾部
        elementData[size++] = e;
        return true;
    }

  1. 將元素添加到指定的位置排截。
/**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        //檢查添加的位置是否超出數(shù)組范圍嫌蚤,超出就拋異常。
        rangeCheckForAdd(index);

        //確認(rèn)數(shù)組的容量断傲,容量不夠的話搬葬,則擴(kuò)容。
        ensureCapacityInternal(size + 1);  // Increments modCount!!
  
        //將指定位置后的元素后移一位艳悔。
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
         
        //將元素插入到數(shù)組指定的位置。
        elementData[index] = element;
        size++;
    }



3.添加一個(gè)集合女仰,不指定位置猜年。直接將集合轉(zhuǎn)換成Object數(shù)組, 然后追加到數(shù)組的最尾端疾忍。

/**
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the
     * specified collection's Iterator.  The behavior of this operation is
     * undefined if the specified collection is modified while the operation
     * is in progress.  (This implies that the behavior of this call is
     * undefined if the specified collection is this list, and this
     * list is nonempty.)
     *
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(Collection<? extends E> c) {
        //將集合轉(zhuǎn)換成Oibject數(shù)組乔外。
        Object[] a = c.toArray();

        //獲取要添加的集合的數(shù)組的長(zhǎng)度。
        int numNew = a.length;
  
        //確認(rèn)新當(dāng)前數(shù)組的容量一罩, 如果不夠杨幼,則擴(kuò)容。
        ensureCapacityInternal(size + numNew);  // Increments modCount
        
        //將對(duì)象數(shù)組添加到當(dāng)前ArrayList數(shù)組的尾端聂渊。
        System.arraycopy(a, 0, elementData, size, numNew);
        
        //size增加差购。
        size += numNew;
        return numNew != 0;
    }


  1. 從指定的位置添加一個(gè)集合。
/**
     * Inserts all of the elements in the specified collection into this
     * list, starting at the specified position.  Shifts the element
     * currently at that position (if any) and any subsequent elements to
     * the right (increases their indices).  The new elements will appear
     * in the list in the order that they are returned by the
     * specified collection's iterator.
     *
     * @param index index at which to insert the first element from the
     *              specified collection
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        //檢查位置是否在數(shù)組范圍內(nèi)
        rangeCheckForAdd(index);
        
        //將需要添加的集合轉(zhuǎn)換成對(duì)象數(shù)組
        Object[] a = c.toArray();

        //獲取對(duì)象數(shù)組的長(zhǎng)度
        int numNew = a.length;

        //確認(rèn)當(dāng)前數(shù)組的容量汉嗽,如果不組欲逃,則擴(kuò)容。
        ensureCapacityInternal(size + numNew);  // Increments modCount

        //確定需要移動(dòng)的元素個(gè)數(shù)
        int numMoved = size - index;

        //如果移動(dòng)的元素個(gè)數(shù)大于0饼暑,則先移動(dòng)數(shù)組元素稳析。
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);

        //將對(duì)象數(shù)組復(fù)制添加到ArrayList的指定位置。
        System.arraycopy(a, 0, elementData, index, numNew);

        //添加元素個(gè)數(shù)
        size += numNew;
        return numNew != 0;
    }



刪除元素

刪除元素有5個(gè)公開(kāi)的方法弓叛。刪除單個(gè)元素用remove() 彰居,有1個(gè)重載。刪除集合用removeAll()或者removeRange()撰筷。 清空集合使用 clear()陈惰。私有方法fastRemove()是執(zhí)行刪除的方法, 判斷要?jiǎng)h除的元素是否處于數(shù)組的末端闭专。如果是則直接將元素指向null奴潘,如果不是旧烧,則移動(dòng)待刪除元素后的元素覆蓋 待刪除元素, 然后將最后一個(gè)元素指向null画髓。

1.根據(jù)索引刪除一個(gè)元素

  /**
     * 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);
        
        //增加修改次數(shù)
        modCount++;
        
        //獲取指定索引的元素掘剪。
        E oldValue = elementData(index);
        
        //計(jì)算出需要移動(dòng)的元素個(gè)數(shù)
        int numMoved = size - index - 1;

        //如果需要移動(dòng)的元素個(gè)數(shù)大于0,則將數(shù)組后面的元素移動(dòng)覆蓋這個(gè)索引元素
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);

        //數(shù)組的總長(zhǎng)度-1奈虾,并且將最后一個(gè)元素指向null
        elementData[--size] = null; // Let gc do its work
        
        //返回刪除元素
        return oldValue;
    }



2.根據(jù)元素對(duì)象刪除元素夺谁。


 /**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If the list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns <tt>true</tt> if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return <tt>true</tt> if this list contained the specified element
     */
    public boolean remove(Object o) {
        //如果傳過(guò)來(lái)的對(duì)象是null。
        if (o == null) {
            //循環(huán)當(dāng)前的數(shù)組肉微,找到等于null的元素匾鸥,并刪除。
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {

            //如果對(duì)象不是null碉纳。循環(huán)當(dāng)前數(shù)組勿负,調(diào)用equals方法找到元素,并刪除劳曹。
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        //如果找到元素并刪除奴愉,就會(huì)在之前返回true。如果都沒(méi)有找到的話铁孵。則沒(méi)有對(duì)應(yīng)的元素锭硼,返回false。
        return false;
    }



3.removeAll方法蜕劝,調(diào)用的是私有的batchRemove()方法檀头。

public boolean removeAll(Collection<?> c) {
        return batchRemove(c, false);
}


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) {
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }



4.removeRange方法刪除指定范圍的元素。


/**
     * Removes from this list all of the elements whose index is between
     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
     * Shifts any succeeding elements to the left (reduces their index).
     * This call shortens the list by {@code (toIndex - fromIndex)} elements.
     * (If {@code toIndex==fromIndex}, this operation has no effect.)
     *
     * @throws IndexOutOfBoundsException if {@code fromIndex} or
     *         {@code toIndex} is out of range
     *         ({@code fromIndex < 0 ||
     *          fromIndex >= size() ||
     *          toIndex > size() ||
     *          toIndex < fromIndex})
     */
    protected void removeRange(int fromIndex, int toIndex) {
        //修改次數(shù)加1
        modCount++;

        //計(jì)算出需要移動(dòng)的元素岖沛。
        int numMoved = size - toIndex;

        //移動(dòng)元素覆蓋掉要?jiǎng)h除的元素暑始。
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // Let gc do its work
        //計(jì)算出刪除后的數(shù)組的大小。
        int newSize = size - (toIndex-fromIndex);
        
        //將已經(jīng)不需要的元素指向null 烫止,讓垃圾收集器進(jìn)行回收蒋荚。
        while (size != newSize)
            elementData[--size] = null;
    }


  1. 清空ArrayList。
 /**
     * Removes all of the elements from this list.  The list will
     * be empty after this call returns.
     */
    public void clear() {
        //修改次數(shù)加1
        modCount++;

        // Let gc do its work
        //循環(huán)將所有數(shù)組元素指向null
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        size = 0;
    }



獲取元素

ArrayList的優(yōu)勢(shì)就在于獲取元素馆蠕。因?yàn)榈讓邮鞘褂脭?shù)組實(shí)現(xiàn)的期升。所以獲取任意位置的元素的時(shí)間復(fù)雜度都是 O(1)。 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) {
        //檢測(cè)索引是否超出范圍播赁。
        rangeCheck(index);
         
        //根據(jù)索引直接返回?cái)?shù)組元素。elementData方法也只是直接返回?cái)?shù)組元素吼渡。
        return elementData(index);
    }


    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }




總結(jié)

ArrayList 的主要方法都沒(méi)有做到線程安全容为。所以單線程的話就使用ArrayList是效率比較高的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市坎背,隨后出現(xiàn)的幾起案子替劈,更是在濱河造成了極大的恐慌,老刑警劉巖得滤,帶你破解...
    沈念sama閱讀 222,590評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件陨献,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡懂更,警方通過(guò)查閱死者的電腦和手機(jī)眨业,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)沮协,“玉大人龄捡,你說(shuō)我怎么就攤上這事】对荩” “怎么了聘殖?”我有些...
    開(kāi)封第一講書(shū)人閱讀 169,301評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)行瑞。 經(jīng)常有香客問(wèn)我就斤,道長(zhǎng),這世上最難降的妖魔是什么蘑辑? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 60,078評(píng)論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮坠宴,結(jié)果婚禮上洋魂,老公的妹妹穿的比我還像新娘。我一直安慰自己喜鼓,他們只是感情好副砍,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,082評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著庄岖,像睡著了一般豁翎。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上隅忿,一...
    開(kāi)封第一講書(shū)人閱讀 52,682評(píng)論 1 312
  • 那天心剥,我揣著相機(jī)與錄音,去河邊找鬼背桐。 笑死优烧,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的链峭。 我是一名探鬼主播畦娄,決...
    沈念sama閱讀 41,155評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了熙卡?” 一聲冷哼從身側(cè)響起杖刷,我...
    開(kāi)封第一講書(shū)人閱讀 40,098評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎驳癌,沒(méi)想到半個(gè)月后滑燃,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,638評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡喂柒,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,701評(píng)論 3 342
  • 正文 我和宋清朗相戀三年不瓶,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片灾杰。...
    茶點(diǎn)故事閱讀 40,852評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蚊丐,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出艳吠,到底是詐尸還是另有隱情麦备,我是刑警寧澤,帶...
    沈念sama閱讀 36,520評(píng)論 5 351
  • 正文 年R本政府宣布昭娩,位于F島的核電站凛篙,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏栏渺。R本人自食惡果不足惜呛梆,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,181評(píng)論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望磕诊。 院中可真熱鬧填物,春花似錦、人聲如沸霎终。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,674評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)莱褒。三九已至击困,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間广凸,已是汗流浹背阅茶。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,788評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留谅海,地道東北人目派。 一個(gè)月前我還...
    沈念sama閱讀 49,279評(píng)論 3 379
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像胁赢,于是被迫代替她去往敵國(guó)和親企蹭。 傳聞我的和親對(duì)象是個(gè)殘疾皇子白筹,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,851評(píng)論 2 361

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