java集合之ArrayList源碼解讀 幫助大家自己動手寫一個ArrayList

java集合之ArrayList源碼解讀 幫助大家自己動手寫一個ArrayList


一、我們知道ArrayList與一般數組最明顯的區別是ArrayList可以存放不同類型的數據,而數組只能存放相同類型的數據。
下面我們來看一下ArrayList底層原理的實現
/**
     * 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.
     */
    transient Object[] elementData; // non-private to simplify nested class access

觀察這段源碼,我們可以知道原來ArrayList是使用Object數組來存放數據的呀!原來本質還是數組。
二、下面通過我們使用ArrayList的過程,將ArrayList的實現原理一一進行解析,最後解析完,大家能夠很輕鬆的寫一個自己的簡化版ArrayList,我的目的也就達成了。
1、首先我們要new一個ArrayList對象,當然通過反射也行,這裏只說最常見的情形。
下面展示ArrayList構造方法底層原理的實現,當然構造方法很多,在這裏只展示無參和帶大小參數的構造函數,感覺是最具代表性。
/**
     * 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.
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
1)無參數的構造函數
/**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
2)帶大小參數的構造函數
/**
     * 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);
        }
    }
通過構造函數我們可以知道,其實new一個ArrayList對象就是給elementData這個對象數組進行初始化的過程。
2、有了ArrayList對象之後,我們就要往裏面存放我們的數據了。
這裏AarryList使用的是add方法,下面展示源碼,並分析算法實現原理,同樣add方法重載的版本很多,在此也只介紹最常見的
/**
     * A version of rangeCheck used by add and addAll.
     */
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }
/**
     * 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++;
    }
算法思想也比較簡單
實現原理是:
(1) 首先判斷初始容量是否足夠,如果不足夠,進行擴容
(2) 在容量足夠的情況下,存放數組
當然上述只是大致原理,還有很多細節需要完善。例如,邊界判斷,擴容算法等等。當然對於寫一個簡單的add方法這些就足夠了。詳細可以參照源碼。

3、有了一個存放了我們需要數據的ArrayList的容器,下面我們要做的就是如何從中獲取我們所需要的數據了。
這裏我們展示ArrayList獲取數據的源碼
/**
     * 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);
    }
通過源碼我們進一步可以知道,ArrayList的底層實現就是數組,這裏ArrayList獲取數據就是通過數組索引進行獲取的。搞清楚了原理之後,這些原來這麼簡單,一點都不難。
4、在說一個非常簡單的方法,獲取ArrayList容器的大小。
不用我貼源碼,我想大家已經知道怎麼實現了。
/**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;
/**
     * Returns the number of elements in this list.
     *
     * @return the number of elements in this list
     */
    public int size() {
        return size;
    }
是不是非常簡單,在ArrayList中,我們會用一個int變量保存容器的大小,獲取時,只需返回就行。如果要問我怎麼保存的,我的回答是在上面的add方法中,就可以看到我們在增加數據時,對應的類成員變量size也會進行動態的變化。當然下面要講的remove方法也是一樣,它也會動態的更新類成員變量size的值。如果還是不太清楚,可以先繼續往下學習,多體會體會就明白了。
5、有增加就會有刪除,下面要說的就是刪除容器的數據了。
在jdk1.8的源碼中使用的時remove方法,下面展示源碼
/*
     * 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 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;
    }

/**
     * 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 ? get(i)==null : 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;
    }
是不是感覺有點複雜,確實是很複雜,但是那是在考慮了很多方面的情況下,我們的目的是爲了弄清原理,所以只需要把握住最核心的部分就可以了。
我把核心代碼粘貼出來
 for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }


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

這裏再次強調ArrayList的底層實現是數組!!!
算法實現原理:
(1) 首先找到要刪除的元素的下標
(2) 之後將該下標之後所有數據全部向前移動一位。
(3) 回收數據,更新容器的大小,使用elementData[--size] = null;
6、類似數據庫的crud,最後再講一下如何修改容器中的數據。
這裏再再次強調ArrayList的底層實現是數組!!!
相信大家不用看我下面的代碼就已經知道怎麼寫了吧!下面我就只粘貼一個非常具有代表性的
 public E set(int index, E e) {
            rangeCheck(index);
            checkForComodification();
            E oldValue = ArrayList.this.elementData(offset + index);
            ArrayList.this.elementData[offset + index] = e;
            return oldValue;
        }
從源代碼我們不難看出,其實用的還是修改數組中元素的方法。直接根據索引找到數據進行賦值修改即可!

原本還想講更多的方法的,但我覺得這些就已經夠了,其它的方法要不就是直接,要不就是間接使用了上述的方法,然後在此基礎上增加一些邏輯而已。所以就不在往下繼續講了。
爲方便大家學習,特別找了一篇實現簡單ArrayList的博客
https://www.cnblogs.com/qifengshi/p/6377614.html

在此感謝您的瀏覽,希望對您有所幫助!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章