ArrayList (jdk1.8)源碼分析

概述

一首古詩句說的好,書中自有黃金屋。作爲一個有追求的程序員,若想寫好代碼,則必須閱讀好的源代碼,並總結吸收其精髓。第一次寫源碼分析的文章,大家多多包涵。

ArrayList 類的繼承關係圖

這裏寫圖片描述
說明:
ArrayList 實現了Iterable接口,說明該類可以通過迭代器遍歷他。
ArrayList 實現了Collection接口,說明該類具有集合常規方法操作。
ArrayList 實現了List接口,說明該類具有線性表操作方法。
ArrayList實現了RandomAccess接口,說明該類可以通過index快速訪問元素。
ArrayList實現了Cloneable接口,說明該類具有clone方法。
ArrayList實現了Serializable接口,說明該類可以進行序列化。

ArrayList 成員變量分析

    //該變量用於類的序列化標識id 
private static final long serialVersionUID = 8683452581122892189L;
    // elementData 爲一個數組,是ArrayLIst真正存放數據的數據結構。
private transient Object[] elementData;
     // size ArrayList中元素個數(標識數組中真正存在元素的個數,非數組真正的長度)。
private int size;

ArrayList 常用方法分析

構造方法

//指定數組初始化長度構造方法
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }
//ArrayList ,默認構造函數,會初始化elementData爲10個長度的object數組;
    public ArrayList() {
        this(10);
    }
//也可以通過傳入一個集合構造一個該集合元素的Arraylist(調用Arrays.copy實現數組copy)。
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }

增加元素方法

//向list尾部添加一個元素
    public boolean add(E e) {
    //確定當前數組容量是否夠用,若不夠用則擴容
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
//向list指定位置添加一個元素
    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++;
    }
    //向容器加入一個集合的元素
    public boolean addAll(Collection<? extends E> c) {
    //獲取待加入集合元素數組
        Object[] a = c.toArray();
        int numNew = a.length;
        //校驗是否需要數組擴容
        ensureCapacityInternal(size + numNew);  // Increments modCount
        //調用native方法將數組copy到指定區域位置
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }
//向容器指定位置加入一個集合的元素(從index開始)
    public boolean addAll(int index, Collection<? extends E> c) {
    //校驗index是否在指定範圍
        rangeCheckForAdd(index);
    //獲取待加入集合元素數組
        Object[] a = c.toArray();
        int numNew = a.length;
         //確定當前數組容量是否夠用,若不夠用則擴容
        ensureCapacityInternal(size + numNew);  // Increments modCount

        int numMoved = size - index;
        //如果index不是數組最後一個元素索引,將原先list中index到size之間的數據平移到index+numNew位置開始到集合末尾的位置
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
//將待加入集合數組元素copy到elementData指定index位置開始後的數據段中
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }

//確認容量是否需要擴容
    private void ensureCapacityInternal(int minCapacity) {
        //modCount 自增標識list內容改變,(迭代器遍歷會通過此變量判斷數據是否改變)。
        modCount++;
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);//若數組容器不夠,則執行grow 函數擴容
    }

 //該變量用來標識數組長度是否快到溢出狀態
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//真正的擴容函數
    private void grow(int minCapacity) {
        // overflow-conscious code
        //記錄之前數組長度
        int oldCapacity = elementData.length;
        //計算新數組長度,爲原來數組長度的1.5倍(擴容長度)
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //數組長度超過int 最大值,則數組不能擴容
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
            //數組擴容長度大於int最大值-8 則執行hugeCapacity函數超過int最大值拋出內存溢出異常,否則擴容到int最大值
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        //通過Arrays.copyOf複製移動數組
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    private static int hugeCapacity(int minCapacity) {
    //內存溢出
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
            //int最大值容量或最大值容量-8
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
    //校驗索引是否超出界限
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

方法執行流程:

這裏寫圖片描述

查找遍歷方法


//是否包含此元素
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
//從頭遍歷循環若找到指定元素,則返回下標(元素可爲null),找不到返回-1
    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

   //從尾部開始遍歷,找到指定元素,返回下標,找不到返回-1
    public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
//訪問數組某個索引的元素
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

  //獲取指定索引的元素
    public E get(int index) {
    //校驗索引範圍
        rangeCheck(index);

        return elementData(index);
    }

 //校驗索引返回,超出size則拋出IndexOutOfBoundsException異常
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    //獲取指定索引開始的,list迭代器
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

   //獲取從list頭部開始遍歷的,list待定器
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

   //獲取list 老版本迭代器
    public Iterator<E> iterator() {
        return new Itr();
    }

   //舊版本迭代器,實現類
    private class Itr implements Iterator<E> {
    //next元素下標索引
        int cursor;       // index of next element to return
     //當前迭代器元素內容,用於刪除List元素
        int lastRet = -1; // index of last element returned; -1 if no such
     //該變量爲了記錄,獲取迭代器時候,list修改狀態的(List不支持多線程
     //當list遍歷的時候,其他線程修改list,會通過該變量,拋出異常)。
        int expectedModCount = modCount;
//時候還有元素
        public boolean hasNext() {
            return cursor != size;
        }
//獲取下個元素
        @SuppressWarnings("unchecked")
        public E next() {
        //校驗List是否修改過
            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();
            }
        }
        //校驗狀態是否變化過
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    /**
     * An optimized version of AbstractList.ListItr
     */
     //優化版本的迭代器 可以獲取指定list遍歷起點的的迭代器 也可以雙向遍歷
    private class ListItr extends Itr implements ListIterator<E> {
    //指定迭代器起始索引的構造方法
        ListItr(int index) {
            super();
            cursor = index;
        }
//是否有前向元素
        public boolean hasPrevious() {
            return cursor != 0;
        }
//獲取next元素索引
        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();
            }
        }
    }

由以上源碼可以知道,我們可以直接通過索引獲取list中的元素。也可以通過for循環遍歷獲取list元素。也可以通過兩種迭代器遍歷list元素。

刪除方法

//通過索引移除元素
    public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        //不是最後一個元素,進行數組平移copy
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // Let gc do its work

        return oldValue;
    }

   //通過元素對象移除
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
            //尋找索引
                if (elementData[index] == null) {
                //快速通過索引刪除,不用校驗index
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
             //尋找索引
                if (o.equals(elementData[index])) {
                //快速通過索引刪除,不用校驗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; // Let gc do its work
    }

//遍歷將清楚List
    public void clear() {
        modCount++;

        // Let gc do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }
//移除指定範圍的list元素
protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // Let gc do its work
        int newSize = size - (toIndex-fromIndex);
        while (size != newSize)
            elementData[--size] = null;
    }

   //索引校驗
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    //移除指定集合內的元素
      public boolean removeAll(Collection<?> c) {
        return batchRemove(c, false);
    }
    //只保留指定集合中的元素
     public boolean retainAll(Collection<?> c) {
        return batchRemove(c, true);
    }


//移除指定集合總的元素
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }

其他方法介紹

//自定義序列化方法
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        // Write out element count, and any hidden stuff
        int expectedModCount = modCount;
        s.defaultWriteObject();

        // Write out array length
        s.writeInt(elementData.length);

        // Write out all elements in the proper order.
        for (int i=0; i<size; i++)
            s.writeObject(elementData[i]);

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

    }

 //自定義反序列化方法
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in size, and any hidden stuff
        s.defaultReadObject();

        // Read in array length and allocate array
        int arrayLength = s.readInt();
        Object[] a = elementData = new Object[arrayLength];

        // Read in all elements in the proper order.
        for (int i=0; i<size; i++)
            a[i] = s.readObject();
    }

總結:

ArrayList 底層通過數組實現。
ArrayList 在插入數據,數組長度不夠,數組會出現擴容,擴容長度爲原來的1.5倍,擴容的過程會出現數組內容copy,更大內存數組生成,比較耗時。
ArrayList 刪除數據的時候,會產生數組平移copy,比較耗時。
ArrayList 查找數據,比較快,可以直接通過下標索引獲取數據。
ArrayList 不支持多線程,通過迭代器遍歷的時候,如果有其他線程刪除或新增元素,會拋出 ConcurrentModificationException()異常。
ArrayList 遍歷刪除元素,最好通過迭代器實現。ArrayList有兩種迭代器,一種只能單向迭代,最新的一種可以雙向,並且指定迭代範圍。
ArrayList 重寫了序列化方法。
希望對您有所幫助!

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