1. 程式人生 > >jdk原始碼淺讀-ArrayList

jdk原始碼淺讀-ArrayList

  一、ArrayList概述

  首先我們來說一下ArrayList是什麼?它解決了什麼問題?ArrayList其實是一個數組,但是有區別於一般的陣列,它是一個可以動態改變大小的動態陣列。ArrayList的關鍵特性也是這個動態的特性了,ArrayList的設計初衷就是為了解決Java陣列長度不可變的問題。我們都知道在Java中陣列一旦被創建出來,那麼這個陣列的大小就不可以改變了,而且初始化的時候就必須要指定陣列的大小。在開發的場景中很多時候我們並不知道我們的資料量有多少,如果陣列建立得太大就會造成極大的空間資源的浪費,如果太小了又會報陣列下標越界異常。這是我們在開發的過程中使用陣列來儲存資料時經常會遇到的問題,但是如果使用ArrayList的話,就可以輕易的解決這個問題,它能夠根據你存放的資料的大小動態的改變陣列的大小(本質建立新陣列),所以我們在寫程式碼的時候就不需要關心陣列的大小了,我覺得這也是ArrayList創建出來所需要解決的問題。當然,如果在知道陣列的大小且對陣列的資料不增加的話,建議使用陣列的儲存資料,這樣對效能的提升有一定的幫助。

  那麼,ArrayList是怎麼動態擴充套件陣列大小的呢?下面通過原始碼一步一步揭開ArrayList的神祕面紗吧。

  

  二、ArrayList全域性變數

     /**
     * Default initial capacity.
     */
    //預設的初始化大小
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 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.
     
*/ //這個是用來存放資料用的陣列,add進來的資料都是放到這個數組裡面的 transient Object[] elementData; // non-private to simplify nested class access /** * The size of the ArrayList (the number of elements it contains). * * @serial */ //陣列的大小 private int size;

  三、ArrayList建構函式

  ArrayList的建構函式有三個:

  1、ArrayList(int initialCapacity):initialCapacity,陣列的初始化大小,該構造器建立一個指定大小的空陣列。

  2、ArrayList():建立一個預設大小為0的空陣列

  3、ArrayList(Collection<? extends E> c):建立一個與c一樣大小的陣列,並將c的元素賦值到陣列中。

**
     * 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) {//建立一個 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) {
        //將c轉換成陣列,toArray方法返回的陣列型別有可能不是Object型別的
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            //陣列型別不是Object型別,需要將型別轉換成Object類,避免後面呼叫方法
            // 的時候出現型別轉換異常
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

  這裡我們主要看一下Arrays.copyOf()方法是如何轉換型別的:

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

  這個方法中,如果傳入的型別為Object型別,那麼就直接建立一個Object陣列,否則建立一個對應型別的陣列。然後呼叫System.arraycopy方法,將原陣列賦值到新建立的陣列中,強調一下,凡是使用到陣列的地方就一定會使用到arraycopy的方法,這個方法我在String原始碼閱讀有說到過,在這裡我再跟大家說一下這個方法吧。

public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

  這是一個本地方法所以無法繼續往下看原始碼了,但是從原始碼中可以知道每個引數代表的含義

  src:原陣列

  srcPos:原陣列中開始複製的位置

  dest:新陣列,即目標陣列

  destPos:目標陣列存放的位置,即從原陣列的複製過來的元素從這個位置開始放

  length:複製陣列的長度

  舉個程式碼示例:

public static void main(String[] args) {
        int[] src = {1,2,3,4,5};
        int[] dest = new int[6];
        for (int i : dest) {
            System.out.print(i + " ");
        }
        System.out.println();
        System.arraycopy(src,0,dest,0,src.length);
        for (int i : dest) {
            System.out.print(i + " ");
        }
    }

    //執行結果:
    //0 0 0 0 0 0 
    //1 2 3 4 5 0 

  看示例程式碼應該能夠懂,第一次列印的時候dest只是被初始化沒有賦值,所以裡面每個元素存放的都是預設值,而int的預設值為0,所以打印出來的都是0,之後arraycopy後將src的所有資料複製到dest從0位置開始,所以列印的結果是 1 2 3 4 5 0

 

  四、add方法

/**
     * 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!!
        //在index位置的元素全部往後移一位,為新增進來的元素騰出一個位置
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        //將元素放入到index位置上
        elementData[index] = element;
        size++;
    }

  新增元素之前都需要檢查一下當前的陣列是否已經滿了,如果滿了就按照新增元素後的大小進行擴容。可以說在整個ArrayList類中最核心的方法就是ensureCapacityInternal了,這個方法就是用來動態擴容的。

private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}

private void ensureExplicitCapacity(int minCapacity) { //修改次數+1,主要實現快速失敗機制的 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; //每次擴容都是擴大原來陣列大小的1.5倍 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: //建立一個新的陣列,長度為 newCapacity,然後將原來陣列的元素複製到新陣列上並返回新陣列,達到動態擴容陣列的目的 elementData = Arrays.copyOf(elementData, newCapacity); }

  在每次新增資料的時候都需要檢查一下新增資料後的長度是否大於當前陣列的長度,大於的話就建立一個大小為原來陣列的1.5倍的新陣列,然後將原陣列的資料都複製到新陣列中,最後將原陣列的引用指向新陣列,從而達到了擴容的目標。

 

  五、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) {
        rangeCheck(index);

        return elementData(index);
    }

// Positional Access Operations

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

  獲取資料的方法比較簡單,直接根據陣列的下標index找到元素就行了,所以查詢的速度比較快。

 

  六、delete方法

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

  刪除有兩個過載的方法,一個是傳入一個數組的下標,另一個是傳入具體的內容,但是最總還是根據equals方法查到index,然後根據index刪除元素。假設有個陣列為 String[] strs = {"a","b","c","d","e"},現在呼叫 remove(3),那個大概流程為:

  

  七、ArrayList的使用:

public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        
        //新增操作
        list.add(1);
        list.add(2);
        list.add(3);
        
        //刪除操作
        list.remove(0);
        
        //查詢操作
        //1、隨機訪問:
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        
        //增強for迴圈遍歷
        for (Integer integer : list) {
            System.out.println(integer);
        }
        //使用迭代器遍歷
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()){
            Integer integer = iterator.next();
            System.out.println(integer);
        }
    }

  八、總結:

  1、ArrayList的增刪改查等所有操作,其內部都是對陣列進行操作。

  2、ArrayList的動態擴容其本質是建立一個更大的陣列。

  3、每次擴容都擴大到原來的1.5倍,1.5倍是比較理想的,如果每次擴容太小的話就會頻繁擴容,每次擴容都需要進行陣列的複製,效能消耗比較大,應該儘量避免。如果擴容的倍數太大可能會造成空間的浪費。

  4、ArrayList允許存放null值。

  

  九、建議:

  1、在知道資料大小且後期不會在新增資料的情況下建議使用陣列,而不是ArrayList;

  2、初始化前估計資料量的大小,儘量指定ArrayList的初始化容量,避免進行頻繁的陣列複製操作;

  3、在刪除比較多場景中不建議使用ArrayList;

  4、在查多刪少的場景中建議使用ArrayList,原因是這個類查詢的速度非常快,時間複雜度為O(1),即不管資料量有多大,查詢速度都一樣的,而且非常快。但是刪除操作是比較慢的,上面我也有提到過,ArrayList中每一次刪除一個數據,後面所有的元素都要往前挪一位。如果資料量非常大,刪除的資料剛好在第一個位置,那個後面的所有元素都要前移,時間複雜度為O(N),這樣是非常耗費時間的。

  5、ArrayList是非執行緒安全的,如果在多執行緒環境中對安全的要求比較高的,建議使用 CopyOnWriteArrayList這個類,不懂得可以百度一下,或者將ArrayList轉成執行緒安全得,使用這種方式就可以:List list = Collections.synchronizedList(new ArrayList());

  

  最後,我自己也手寫了一個ArrayList,基本功能都能夠實現,專案地址:https://github.com/rainple1860/MyCollection