當(dāng)前位置:首頁 > IT技術(shù) > 編程語言 > 正文

Java Review - ArrayList 源碼解讀
2021-11-16 11:28:04

Java Review - ArrayList 源碼解讀_ArrayList


概述

Java Review - ArrayList 源碼解讀_i++_02

從類的繼承圖上我們可知道,ArrayList實現(xiàn)了List接口。

  • 同時List是順序容器,即元素存放的數(shù)據(jù)與放進(jìn)去的順序相同,允許放入null元素,

  • ArrayList底層基于數(shù)組實現(xiàn)。

  • 每個ArrayList都有一個容量(capacity),表示底層數(shù)組的實際大小,容器內(nèi)存儲元素的個數(shù)不能多于當(dāng)前容量。

  • 當(dāng)向容器中添加元素時,如果容量不足,容器自動擴(kuò)容。

  • ArrayList<E>,可以看到是泛型類型, Java泛型只是編譯器提供的語法糖,數(shù)組是一個Object數(shù)組,可以容納任何類型的對象。
    Java Review - ArrayList 源碼解讀_添加數(shù)據(jù)_03

Java Review - ArrayList 源碼解讀_i++_04


方法的執(zhí)行效率

Java Review - ArrayList 源碼解讀_i++_05

  • size(), isEmpty(), get(), set()方法均能在常數(shù)時間內(nèi)完成
  • add()方法的時間開銷跟插入位置有關(guān)
  • addAll()方法的時間開銷跟添加元素的個數(shù)成正比。
  • 其余方法大都是線性時間。

為追求效率,ArrayList沒有實現(xiàn)同步(synchronized),如果需要多個線程并發(fā)訪問,用戶可以手動同步,也可使用Vector替代


源碼剖析

底層數(shù)據(jù)結(jié)構(gòu) -數(shù)組

Java Review - ArrayList 源碼解讀_ArrayList_06


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

Java Review - ArrayList 源碼解讀_ArrayList_07

  /**
     * 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) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        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) {
        Object[] a = c.toArray();
        if ((size = a.length) != 0) {
            if (c.getClass() == ArrayList.class) {
                elementData = a;
            } else {
                elementData = Arrays.copyOf(a, size, Object[].class);
            }
        } else {
            // replace with empty array.
            elementData = EMPTY_ELEMENTDATA;
        }
    }

Java Review - ArrayList 源碼解讀_添加數(shù)據(jù)_08

演示如下:


        /**
         * 初始化的時候指定容量
         */
        List list = new ArrayList<>(1);
        list.add(1);
        list.add(2);
        System.out.println(list.size());

        /**
         * 默認(rèn)構(gòu)造函數(shù) ,數(shù)組大小為0
         */
        list = new ArrayList();
        list.add("artisan");
        list.add("review");
        list.add("java");
        System.out.println(list.size());



        /**
         * 使用集合初始化一個ArrayList
         */
        list = new ArrayList(Arrays.asList("I" , "Love" ,"Code"));
        System.out.println(list.size());



自動擴(kuò)容機(jī)制

  • 每當(dāng)向數(shù)組中添加元素時,都需要檢查添加后元素的個數(shù)是否會超出當(dāng)前數(shù)組的長度,如果超出,數(shù)組將會進(jìn)行擴(kuò)容,以滿足添加數(shù)據(jù)的需求。
    Java Review - ArrayList 源碼解讀_ArrayList_09

  • 數(shù)組進(jìn)行擴(kuò)容時,會將老數(shù)組中的元素重新拷貝一份到新的數(shù)組中,每次數(shù)組容量的增長大約是其原容量的1.5倍。

    這種操作的代價是很高的,因此在實際使用時,我們應(yīng)該盡量避免數(shù)組容量的擴(kuò)張。當(dāng)我們可預(yù)知要保存的元素的多少時,要在構(gòu)造ArrayList實例時,就指定其容量,以避免數(shù)組擴(kuò)容的發(fā)生。

    或者根據(jù)實際需求,通過調(diào)用ensureCapacity方法來手動增加ArrayList實例的容量。

Java Review - ArrayList 源碼解讀_添加數(shù)據(jù)_10

  • ArrayList#ensureCapacity(int minCapacity)暴漏了public方法可以允許程序猿手工擴(kuò)容增加ArrayList實例的容量,以減少遞增式再分配的數(shù)量。

我們來看下效率對比

 /**
         * 擴(kuò)容對比
         */

        long begin = System.currentTimeMillis();
        // 初始化1億的數(shù)據(jù)量
        final int number = 100000000 ;
        Object o = new Object();
        ArrayList list1 = new ArrayList<String>();
        for (int i = 0; i < number; i++) {
            list1.add(o);
        }
        System.out.println("依賴ArrayList的自動擴(kuò)容機(jī)制,添加數(shù)據(jù)耗時:" +(System.currentTimeMillis() - begin));


        begin = System.currentTimeMillis();
        ArrayList list2 = new ArrayList<String>();
        // 手工擴(kuò)容
        list2.ensureCapacity(number);
        for (int i = 0; i < number; i++) {
            list2.add(o);
        }
        System.out.println("手工ensureCapacity擴(kuò)容后,添加數(shù)據(jù)耗時:" + (System.currentTimeMillis() - begin));


Java Review - ArrayList 源碼解讀_i++_11
原因是因為,第一段如果沒有一次性擴(kuò)到想要的最大容量的話,它就會在添加元素的過程中,一點一點的進(jìn)行擴(kuò)容,要知道對數(shù)組擴(kuò)容是要進(jìn)行數(shù)組拷貝的,這就會浪費大量的時間。如果已經(jīng)預(yù)知容器可能會裝多少元素,最好顯示的調(diào)用ensureCapacity這個方法一次性擴(kuò)容到位。

過程圖如下:

Java Review - ArrayList 源碼解讀_數(shù)組_12


set()

底層是一個數(shù)組, 那ArrayList的set()方法也就是直接對數(shù)組的指定位置賦值

    /**
     * Replaces the element at the specified position in this list with
     * the specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        rangeCheck(index);

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

get

get()方法也很簡單,需要注意的是由于底層數(shù)組是Object[],得到元素后需要進(jìn)行類型轉(zhuǎn)換。

  /**
     * 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);

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


add()/addAll()

這兩個方法都是向容器中添加新元素,這可能會導(dǎo)致capacity不足,因此在添加元素之前,都需要進(jìn)行剩余空間檢查,如果需要則自動擴(kuò)容。擴(kuò)容操作最終是通過grow()方法完成的

/**
     * 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) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    /**
     * 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) {
        rangeCheckForAdd(index);

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

Java Review - ArrayList 源碼解讀_ArrayList_13

  • add(E e) 在末尾添加
  • add(int index, E e)需要先對元素進(jìn)行移動,然后完成插入操作,也就意味著該方法有著線性的時間復(fù)雜度。

Java Review - ArrayList 源碼解讀_數(shù)組_14

  • addAll()方法能夠一次添加多個元素,根據(jù)位置不同也有兩個把本

    一個是在末尾添加的addAll(Collection<? extends E> c)方法,

    一個是從指定位置開始插入的addAll(int index, Collection<? extends E> c)方法。

    跟add()方法類似,在插入之前也需要進(jìn)行空間檢查,如果需要則自動擴(kuò)容;如果從指定位置插入,也會存在移動元素的情況。]

    addAll()的時間復(fù)雜度不僅跟插入元素的多少有關(guān),也跟插入的位置相關(guān)。

 /**
     * 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) {
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

    /**
     * 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) {
        rangeCheckForAdd(index);

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


remove()

remove()方法也有兩個方法

  • 一個是remove(int index)刪除指定位置的元素
  • 一個是remove(Object o)刪除第一個滿足o.equals(elementData[index])的元素
 /**
     * 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);

        modCount++;
        E oldValue = elementData(index);

        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

        return oldValue;
    }

刪除操作是add()操作的逆過程,需要將刪除點之后的元素向前移動一個位置。需要注意的是為了讓GC起作用,必須顯式的為最后一個位置賦null值。

上面代碼中如果不手動賦null值,除非對應(yīng)的位置被其他元素覆蓋,否則原來的對象就一直不會被回收。


    /**
     * 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) {
        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;
    }

Java Review - ArrayList 源碼解讀_ArrayList_15


trimToSize()

將底層數(shù)組的容量調(diào)整為當(dāng)前列表保存的實際元素的大小

  /**
     * Trims the capacity of this <tt>ArrayList</tt> instance to be the
     * list's current size.  An application can use this operation to minimize
     * the storage of an <tt>ArrayList</tt> instance.
     */
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

indexOf(), lastIndexOf()

獲取元素的第一次出現(xiàn)的index

   /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     */
    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;
    }

獲取元素的最后一次出現(xiàn)的index

    /**
     * Returns the index of the last occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the highest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     */
    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;
    }


Fail-Fast

ArrayList同樣采用了快速失敗的機(jī)制,通過記錄modCount參數(shù)來實現(xiàn)。在面對并發(fā)的修改時,迭代器很快就會完全失敗,而不是冒著在將來某個不確定時間發(fā)生任意不確定行為的風(fēng)險。

具體參考前段時間寫的一篇博文如下:

Java - Java集合中的快速失敗Fail Fast 機(jī)制

Java Review - ArrayList 源碼解讀_添加數(shù)據(jù)_16

本文摘自 :https://blog.51cto.com/u

開通會員,享受整站包年服務(wù)立即開通 >