深入Collection之ArrayList

深入集合之ArrayList

​ 集合作爲JDK中使用最頻繁的幾個類之一,對於其具體實現形式的瞭解一直浮於表面。因此查看幾個集合類的源碼(本人以JDK8爲參考源碼)後有了接下來的幾篇博文。而ArrayList作爲使用做頻繁的List,則理所當然是第一篇解析目標:

​ 一個類的組成都是成員變量和成員方法,再細分看就是構造方法和其他方法。而一個類除非使用靜態工廠生成實例,都擺脫不了用構造方法生成實例。因此以後都是以從成員變量到構造方法到其他方法的順序學習集合類。

成員變量

 /**
     * Default initial capacity.
     * 默認的初始容量,即對應數組的大小
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     * 爲空白實例準備的共享空數組(空ArrayList的elementData都指向這個空白數組)
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 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.
     * 爲默認空實例準備的空數組,和EMPTY_ELEMENTDATA唯一不同的是當第一個元素被添加後
     * ,數組elementData的長度被擴展到10
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 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.
     * ArrayList中的元素實際存儲的數組。ArrayList的容量爲這個數組的長度。當一個空白
     * ArrayList且它的elementData爲DEFAULTCAPACITY_EMPTY_ELEMENTDATA添加第一個元
     * 素時,數組長度擴展到10
     */
    transient Object[] elementData; // non-private to simplify nested class access

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

構造方法

  1. 無參構造

    public ArrayList() {
           this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
       }

    初始化一個空的ArrayList,但是capacity在添加第一個元素時變爲10.

  2. 參數爲capacity的構造方法

    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);
           }
       }

    根據初始化的capacity初始化不同的數組。

  3. 參數爲collection的構造方法

    public ArrayList(Collection<? extends E> c) {
           elementData = c.toArray();
           if ((size = elementData.length) != 0) {
               // c.toArray might (incorrectly) not return Object[] (see 6260652)
               if (elementData.getClass() != Object[].class)
                   elementData = Arrays.copyOf(elementData, size, Object[].class);
           } else {
               // replace with empty array.
               this.elementData = EMPTY_ELEMENTDATA;
           }
       }

    ​ 因爲ArrayList的操作實際都轉化到對elementData的操作。所以可以看到這個構造方法的關鍵在toArray()Arrays.copyOf()的操作。除此之外,無非是對集合元素的類型判斷,默認爲Object類型,如果不是,則重新造型。

其他成員方法

在衆多方法中,先介紹幾個使用頻率最高,參與最緊密的。

toArray()
 public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

​ 將ArrayList轉化成數組的關鍵無疑還在Arrays.copyOf()中,只是默認轉化的數組類型和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;
    }

​ 如果newType是Object類,那麼新建Object數組,長度爲newLength。如果不是,則使用Native方法,根據ComponentType和長度生成對應類型數組。再使用Native方法將數據從源數組轉移到新建數組。

數組動態擴容
/*  public方法,對象可以在外部調用擴容。
    一個數組有三種情況:
    1、初始值爲EMPTY_ELEMENTDATA  
    2、初始值爲DEFAULTCAPACITY_EMPTY_ELEMENTDATA
    3、非空數組
    如果源數組爲情況1或3,將入參minCapacity代入擴容。
    如果源數組爲情況2,那麼默認最小擴展爲10,將minCapacity與10比較後擴容。此處可以看出源數組爲           DEFAULTCAPACITY_EMPTY_ELEMENTDATA的差異。
*/
public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            // any size if not default element table
            ? 0
            // larger than default for default empty table. It's already
            // supposed to be at default size.
            : DEFAULT_CAPACITY;

        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }
    /*
        數組增加前做的擴容操作。如果源數組是DEFAULTCAPACITY_EMPTY_ELEMENTDATA,默認擴容至大小爲10.
        如果minCapacity比DEFAUL_CAPACITY大,則擴容至minCapacity。
    */
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_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);
    }

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

    /**
     *  數組擴容的實際操作
     *  將minCapacity和和源數組長度的1.5倍(實際爲右移一位,近似看爲0.5倍)比較,取較大值。
     *  如果增長後的newCapacity比MAX_ARRAY_SIZE大,那麼進入hugeCapacity()方法取擴展後的數組大小。
     *  最後使用Arrays.copyOf()生成一個新的長度爲newCapacity的數組,且內容爲源數組內容。
     */
    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);
    }
    //擴容更小的參數都超出int,那麼拋出Error
    //否則給一個最大限定值。
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

​ 以上代碼可以呼應構造方法中,當elementData爲DEFAULTCAPACITY_EMPTY_ELEMENTDATA時,只要發生數組擴容,默認擴容到數組長度爲10。

List增刪方法
E elementData(int index) {
        return (E) elementData[index];
    }

    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

    public E set(int index, E element) {
        rangeCheck(index);

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

    //添加到數組尾部,先進行數組擴容,再直接對index爲size++處賦值。
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    //先進行數組擴容,再使用Native方法將數組從index以後的值複製到以index+1爲開頭處,再將index賦上
    //新增的element
    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++;
    }

    //幾乎是增加的反過程,還是arraycopy方法。將index後的值複製到index起始的位置。
    //需要注意消除引用,防止內存無法回收。
    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;
    }

    //遍歷找出第一個Object的索引值index,再根據index刪除。
    //同樣需要注意消除應用
    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 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
    }


    public void clear() {
        modCount++;

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

        size = 0;
    }

    //操作過程相似:數組擴容,將新增c轉換成的數組a添加到elementData尾部。同樣通過arraycopy方法。
    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;
    }

    //step1:數組擴容
    //step2:數組index後內容後移
    //step3:將新增數組c內容複製到elementData中。
    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;
    }


    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

​ 從以上增刪操作代碼,可以看出涉及到的操作主要關於增加時的數組動態擴容和使用System.arraycopy()方法完成的數組移動(本質上也是數組複製)和數組複製,和刪除時的同樣使用System.arraycopy()完成數組移動和消除數組引用。

迭代器
 public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    /**
     * Returns a list iterator over the elements in this list (in proper
     * sequence).
     *
     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
     *
     * @see #listIterator(int)
     */
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    /**
     * 返回一個迭代器
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * 重寫Iteartor接口的實現類
     */
    private class Itr implements Iterator<E> {
        int cursor;       // 下一個返回元素的位置
        int lastRet = -1; // 最後一個返回元素的位置
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size;
        }
        //初始化時,從index爲0開始返回。
        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
        //移除當前指向位置元素
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    /**
     * 支持從某個index開始遍歷,可以向前訪問。
     */
    private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }

        public boolean hasPrevious() {
            return cursor != 0;
        }

        public int nextIndex() {
            return cursor;
        }

        public int previousIndex() {
            return cursor - 1;
        }

        @SuppressWarnings("unchecked")
        public E previous() {
            checkForComodification();
            int i = cursor - 1;
            if (i < 0)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i;
            return (E) elementData[lastRet = i];
        }

        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        public void add(E e) {
            checkForComodification();

            try {
                int i = cursor;
                ArrayList.this.add(i, e);
                cursor = i + 1;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

使用迭代器本意是想在不暴露類的內部實現的前提下,可以保證一致的遍歷訪問。

//遍歷刪除問題
public static List<String> initialList(){
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        return list;
    }

    public static void removeByFor(List<String> list){
        for (int i = 0; i < list.size(); i++) {
            if("b".equals(list.get(i))){
                System.out.println(i);
                list.remove(i);
            }
            if("d".equals(list.get(i))){
                System.out.println(i);
                list.remove(i);
            }
        }
        System.out.println(list);
    }

    public static void removeByForeach(List<String> list){
        for (String string : list) {
            if ("b".equals(string)) {
                list.remove(string);
            }
        }
        System.out.println(list);
    }

    public static void removeByIterator(List<String>list){
        Iterator<String> e = list.iterator();
        while (e.hasNext()) {
            String item = e.next();
            if ("b".equals(item)) {
                e.remove();
            }
        }
        System.out.println(list);
    }

    public static void main(String []args){
        removeByFor(initialList());         //1
        removeByForeach(initialList());     //2
        removeByIterator(initialList());    //3
    }
  • 方法1:雖然刪除沒問題,但可能遇到索引值與原數組索引不同的情況.
  • 方法2:刪除拋出 java.util.ConcurrentModificationException。因爲foreach內部使用iteartor實現,導致modCount和expectedModCount不一致。
  • 方法3:遍歷刪除最優解。
SubList

截取ArrayList從fromIndex到toIndex的部分。個人認爲實現沒有其他難點,關鍵點在於所有的增刪操作都是作用於源ArrayList,因此使用時請注意這點。

結語

  • ArrayList內部實現是基於數組,因此需要重點關注動態擴容數組拷貝,從最外看到的index的改變其實是數組下標的改變,而數組下標的改變其實是使用Native方法arraycopy()。
  • get()是常數級的時間複雜度,這比較於LinkedList強大很多。
  • add(E e)直接添加到數組尾部,常數級時間複雜度。
  • add(int index,E e) O(n)時間複雜度。越靠近數組首部需要移動的元素項越多。
  • remove(int index) O(n)時間複雜度。越靠近數組首部需要移動的元素項越多。
  • remove(Object o) O(n)時間複雜度。但是需要先遍歷找到o,比上一種remove耗時長。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章