分析輪子(一)-ArrayList.java

前言:以前也看過一些JDK源碼,不過沒有留下痕跡,經久年月就淡忘了,如今的時機也差很少了,想再看一次,而且記錄下來本身的感想,因而從本身使用最多最熟悉的地方開始!而且看的過程當中,我但願本身思考一下以下的問題:數組

1:若是讓我設計,我怎麼玩?數據結構

2:原做者爲何這樣設計?app

3:它的底層實現是什麼玩意?有什麼特色?dom

4:平時使用的時候,須要注意些什麼東西?函數

5:原設計有什麼特別好玩的點?性能

 

注:玩的是JDK1.7版本ui

 

一:先上類的繼承結構圖this

細細看上圖,其實就能透露出一些關鍵的信息,好比:spa

1:實現Serializable接口,表示ArrayList是可序列化的設計

2:實現RandomAccess接口,表示ArrayList是可快速隨機訪問的

3:實現Cloneable接口,表示ArrayList是能夠調用Object.clone方法的

4:實現Iterable接口,表示容許ArrayList使用迭代遍歷的方式循環

 

二:再看一下他的底層實現數據結構

三:而後從源碼中找點好玩的東西

從源碼中能夠看出ArrayList的底層數據結構是一個數組,因此,它全部的操做都是圍繞着數組來玩的。

1)觀察以下代碼,咱們能夠了解到以下信息

     private 表示不能被類外操做

     transient 表示經過實現Serializable接口的方式來序列化時,被其標識的類變量能夠不被序列化

    Object[] 表示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 == EMPTY_ELEMENTDATA will be expanded to
     * DEFAULT_CAPACITY when the first element is added.
     */
    private transient Object[] elementData;

 

2)size表示數組中元素的個數,對於數組數據結構而言,數據長度至關重要

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

3)觀察以下源碼,咱們能夠看到以下信息

   ArrayList的無參構造函數,初始化的數組對象是一個空數組

   ArrayList的有參構造函數,初始化的對象是根據指定的空間大小來分配數組的空間的

   ArrayList是一個動態擴展的數據集合從 grow 方法中可見一二,而且當它的空間不夠的時候會擴展爲(大概是這樣他還有一些最大最小長度的判斷邏輯): 原總長度+原總長度的一半

   固然ArrayList的元素的值也是有限的最大是 Integer.MAX_VALUE

    /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};
    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        super();
        this.elementData = EMPTY_ELEMENTDATA;
    }
    /**
     * 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];
    }
    /**
     * 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;
    }
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        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;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        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 = 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;
    }
    /**
     * 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
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

 4)觀察以下源代碼,能夠看到ArrayList是能夠放null的,而且刪除元素涉及到數據的移位複製操做是比較耗費性能的

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

四:小結

經過觀察ArrayList的源碼,發現以下一些特色:

1:ArrayList的底層數據結構是數組,全部,數組這種數據結構的特色ArrayList應該也是具備的,這是他的本質

2:數組或者ArrayList這種數據結構的特色是,隨機訪問、循環遍歷等性能好,指定位置插入或刪除元素會涉及數組元素的複製,性能較差

3:ArrayList的底層數據是Object[],因此,具備很好的通用性,null也是能夠存入ArrayList中的

4:ArrayList在添加元素的時候,首先會進行容量檢測,若是不夠會進行動態擴容

5:ArrayList使用的很是之多,使用起來也很是簡單,不過看源碼並不複雜,可是有些東西若是徹底弄清楚也非易事,下面我會補充一些內容以供掃除閱讀源碼產生的一些障礙

相關文章
相關標籤/搜索