ArrayList源碼分析

【補(bǔ)充說明:】

【modCount】
 在父類AbstractList中定義了一個(gè)int型的屬性:modCount,記錄了ArrayList結(jié)構(gòu)性變化的次數(shù)。
 protected transient int modCount = 0; *  在ArrayList的所有涉及結(jié)構(gòu)變化的方法中都增加modCount的值,包括:add()、remove()、addAll()、removeRange()及clear()方法。這些方法每調(diào)用一次,modCount的值就加1。
 注:add()及addAll()方法的modCount的值是在其中調(diào)用的ensureCapacity()方法中增加的。
 
 【調(diào)用add()方法時(shí),調(diào)用的函數(shù):】
程序調(diào)用add,實(shí)際上還會(huì)進(jìn)行一系列調(diào)用,可能會(huì)調(diào)用到grow,grow可能會(huì)調(diào)用hugeCapacity。
 add ——>ensureCapacityInternal  ——>ensureExplicitCapacity - - ->grow - - ->hugeCapacity
 添加 確保內(nèi)部容量(是否擴(kuò)容)            確保明確的容量  擴(kuò)容函數(shù)         指定新容量
    實(shí)例看圖
 
    【總結(jié)】:
        增:僅是將這個(gè)元素添加到末尾。操作快速
        刪:由于需要移動(dòng)插入位置后的元素,并且涉及到數(shù)組的復(fù)制。操作較慢
        改:直接對(duì)指定位置元素進(jìn)行修改,不涉及元素的挪動(dòng)和數(shù)組賦值。操作快速
        查:直接返回指定下標(biāo)的數(shù)組元素。操作快速
    
        ArrayList有其特殊的應(yīng)用場景,與LinkedList相對(duì)應(yīng)。其優(yōu)點(diǎn)是隨機(jī)讀取,
     缺點(diǎn)是插入元素時(shí)需要移動(dòng)大量元素,效率不太高。[查找修改快而插入刪除慢的特點(diǎn)]
ArrayList實(shí)例01(數(shù)組).png
ArrayList實(shí)例02(數(shù)組).png

【ArrayList的一些屬性:】

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    /**
     * 版本號(hào)
     */
    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í)例的共享空數(shù)組實(shí)例 (空對(duì)象數(shù)組)
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};
 /**
     * Shared empty array instance used for default sized empty instances(實(shí)例). We
     * distinguish(區(qū)分) this from EMPTY_ELEMENTDATA to know how much to inflate(膨脹) when
     * first element(元素) is added.
     * 用于默認(rèn)大小的空實(shí)例的共享空數(shù)組實(shí)例。我們將此與EMPTY_ELEMENTDATA區(qū)分開來,以了解何時(shí)
     *  膨脹多少第一個(gè)元素被添加(默認(rèn)長度的空對(duì)象數(shù)組)
     *  DEFAULTCAPACITY_EMPTY_ELEMENTDATA
          默認(rèn)長度       空      元素?cái)?shù)據(jù)
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * The array buffer into which the elements of the ArrayList are stored(存儲(chǔ)).
     * 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.
     *
     * ArrayList的元素存儲(chǔ)在其中的數(shù)組緩沖區(qū)。ArrayList的容量是此數(shù)組緩沖區(qū)的長度。
     *      任何使用elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA為空的ArrayList
     *      將在添加第一個(gè)元素時(shí)擴(kuò)展到DEFAULT_CAPACITY。(元素?cái)?shù)組)
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     * 實(shí)際元素大小,默認(rèn)為0
     * @serial
     */
    private int size;

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

 /**
     * Constructs an empty list with the specified(指定) initial capacity.
     *  構(gòu)造具有指定初始容量的空列表
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    public ArrayList(int initialCapacity) {
        //初始容量大于0
        if (initialCapacity > 0) {
            //初始化元素?cái)?shù)組
            this.elementData = new Object[initialCapacity];
            //初始容量為0
        } else if (initialCapacity == 0) {
            //元素?cái)?shù)組 = (空數(shù)組實(shí)例/空對(duì)象數(shù)組)
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            //初始容量小于0,拋出異常
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructs an empty list with an initial capacity(容量) of ten.
     * 構(gòu)造一個(gè)初始容量為10的空列表
     */
    public ArrayList() {
        //無參構(gòu)造函數(shù),設(shè)置元素?cái)?shù)組為空,長度為10
        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.
     *  構(gòu)造一個(gè)包含指定集合元素的列表,其順序由集合的迭代器返回。
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     * 集合參數(shù)構(gòu)造函數(shù)
     */
    public ArrayList(Collection<? extends E> c) {
        //轉(zhuǎn)換為數(shù)組
        elementData = c.toArray();
        //參數(shù)為非空集合
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            //是否成功轉(zhuǎn)換為Object類型數(shù)組
            if (elementData.getClass() != Object[].class)
                //不為Object數(shù)組,進(jìn)行復(fù)制
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace(替換) with empty array. 替換為空數(shù)組
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

【擴(kuò)容相關(guān)下函數(shù):】

//按照函數(shù)名意為:確保內(nèi)部容量 函數(shù) / 擴(kuò)容函數(shù)
    private void ensureCapacityInternal(int minCapacity) {
        //判斷元素?cái)?shù)組是否為空數(shù)組 (DEFAULTCAPACITY_EMPTY_ELEMENTDATA 默認(rèn)長度的空對(duì)象數(shù)組))
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            //取較大值(默認(rèn)初始容量,傳入的最小容量)
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        //調(diào)用【確保明確的容量】 函數(shù);數(shù)組已經(jīng)初始化過就執(zhí)行這一步
        ensureExplicitCapacity(minCapacity);
    }
    
    //按照函數(shù)名意為:確保明確的容量 函數(shù)
    private void ensureExplicitCapacity(int minCapacity) {
        //結(jié)構(gòu)性 修改時(shí)+1
        modCount++;

        // overflow-conscious code
        //當(dāng)傳入的最小容量 減去 元素?cái)?shù)組的長度 大于0時(shí),需要進(jìn)行擴(kuò)容
        if (minCapacity - elementData.length > 0)
            //調(diào)用 【grow函數(shù)】對(duì)數(shù)組進(jìn)行擴(kuò)容
            grow(minCapacity);
    }

    /**
     * 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
     *  最大數(shù)組容量(集合最大容量)
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     * 增加容量以確保它至少可以容納由參數(shù)指定的元素?cái)?shù)。
     *
     * @param minCapacity the desired minimum capacity
     * 擴(kuò)容函數(shù)
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        //獲取數(shù)組的舊容量
        int oldCapacity = elementData.length;
        //新容量為舊容量的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            //當(dāng)新容量 減去 傳入的最小容量 小于0時(shí),將傳入的最小容量賦值給 新容量
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            //如果 新容量 減去 最大數(shù)組容量 大于0,
            newCapacity = hugeCapacity(minCapacity);    //指定新容量
        // minCapacity is usually close to size, so this is a win:
        //Arrays.copyOf功能是實(shí)現(xiàn)數(shù)組的復(fù)制,返回復(fù)制后的數(shù)組。參數(shù)是被復(fù)制的數(shù)組和復(fù)制的長度:
        //拷貝擴(kuò)容
        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;
    }

【增刪改查函數(shù):】

/**
     * 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) {
        //檢驗(yàn)索引是否合法
        rangeCheck(index);
        //返回索引下標(biāo)所對(duì)應(yīng)的值
        return elementData(index);
    }

    /**
     * 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}
     * 【設(shè)定指定下標(biāo)索引的元素值】
     */
    public E set(int index, E element) {
        //校驗(yàn) 索引是否合法(index 不能 大于 size)
        rangeCheck(index);
        //舊值
        E oldValue = elementData(index);
        //賦新值
        elementData[index] = element;
        //返回舊值
        return oldValue;
    }

    /**
     * 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)部容量】函數(shù):參數(shù)為(實(shí)際元素大小+1)
        //添加之前先檢查是否需要擴(kuò)容,此時(shí)數(shù)組長度最小為size+1
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //將元素添加到數(shù)組末尾
        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);
        //檢查是否需要擴(kuò)容
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //挪動(dòng)插入位置后面的元素
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        //在要插入的位置賦上新值
        elementData[index] = element;
        size++;
    }

    /**
     * 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);
        //需要移動(dòng)的元素的個(gè)數(shù)
        int numMoved = size - index - 1;
        if (numMoved > 0)
            /**
             * Object src :源數(shù)組
             * int srcPos :在源數(shù)組中的起始位置
             * Object dest:目標(biāo)數(shù)組
             * int destPos:在目標(biāo)數(shù)組中的起始位置
             * int length :要復(fù)制的數(shù)組元素的數(shù)量
             */
            //void java.lang.System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
            System.arraycopy(elementData, index+1, elementData, index,numMoved);
        //賦值為空,有利于進(jìn)行GC                   
        elementData[--size] = null; // clear to let GC do its work
        //返回舊值
        return oldValue;
    }

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

    /*
     * Private remove method that skips bounds checking and does not
     * return the value removed.
     */
    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
    }

    /**
     * Removes all of the elements from this list.  The list will
     * be empty after this call returns.
     */
    public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

    /**
     * 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;
        //檢查是否需要擴(kuò)容
        ensureCapacityInternal(size + numNew);  // Increments modCount
        //挪動(dòng)插入位置后面的元素
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }
最后編輯于
?著作權(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),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • ArrayList是在Java中最常用的集合之一,其本質(zhì)上可以當(dāng)做是一個(gè)可擴(kuò)容的數(shù)組,可以添加重復(fù)的數(shù)據(jù),也支持隨...
    ShawnIsACoder閱讀 616評(píng)論 4 7
  • ArrayList ArrayList就是傳說中的動(dòng)態(tài)數(shù)組,就是Array的復(fù)雜版本,它提供了如下一些好處:動(dòng)態(tài)的...
    史路比閱讀 291評(píng)論 0 0
  • 首先看一下集合體系繼承樹 Collection接口 Collection是最基本的集合接口,一個(gè)Collectio...
    SnowDragonYY閱讀 1,322評(píng)論 0 2
  • 每個(gè) ArrayList 實(shí)例都有一個(gè)容量,該容量是指用來存儲(chǔ)列表元素的數(shù)組的大小。它總是至少等于列表的大小。隨著...
    Mervyn_2014閱讀 256評(píng)論 0 0
  • ArrayList 原文見:Java 容器源碼分析之 ArrayList 概述 ArrayList是使用頻率最高的...
    Leocat閱讀 266評(píng)論 0 0

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