JDK源碼那些事兒之經常使用的ArrayList

前面已經講解集合中的HashMap而且也對其中使用的紅黑樹結構作了對應的說明,此次就來看下簡單一些的另外一個集合類,也是平常常用到的ArrayList,總體來講,算是比較好理解的集合了,一塊兒來看下java

前言

jdk版本:1.8

類定義

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  • 繼承了AbstractList,實現了List,提供對數組隊列的增刪改查操做
  • 實現RandomAccess接口,提供隨機訪問功能
  • 實現Cloneable接口,提供克隆功能
  • 實現Serializable接口,支持序列化,方便序列化傳輸

ArrayList繼承關係

變量說明

private static final long serialVersionUID = 8683452581122892189L;

    /**
     * 默認的初始化容量
     * 這裏和HashMap初始容量不一樣,默認10
     * 有些面試官可能問,雖然我感受不必記這玩意
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 空集合,在構造函數中看說明
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 默認容量大小的空集合,這裏和上邊同樣,可是第一次添加的時候會自動擴容到默認容量,看構造函數的說明
     */
    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.
     * 
     * 基於數組實現容量大小變化,上邊註釋也說了第一次添加元素時,將容量擴展到DEFAULT_CAPACITY
     * 更詳細的接着往下看
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * 數組長度,即arraylist的長度
     */
    private int size;
    
    /**
     * 最大數組長度限制
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

從上邊變量定義也能看出來ArrayList本質上是基於Object[]實現,故方法上的操做都是基於數組來進行面試

構造方法

從構造方法中能看出:數組

  • 若是不設置初始化容量或者初始化賦值集合則elementData賦值爲空數組而不是默認容量爲10的數組
/**
     * 無參構造方法,初始化爲默認空數組
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        // 原集合不爲空,則進行復制
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            /**
             * 官方bug
             * c.toArray() 返回類型取決於其實際類型
             * 查了下,應該是調用子類的toArray(重寫)方法返回具體的類型
             * 本身多想下也明白了,父類保存了子類的數組對象,這裏須要調整成Object[]
             * 不明白的本身Google下
             */ 
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // 原集合爲空,elementData賦值爲空數組
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
    /**
     * 初始化容量 代碼比較簡單
     */
    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);
        }
    }

重要方法

add

每次增長元素時會經過ensureCapacityInternal進行容量大小的驗證,不知足則進行擴容操做,經過grow方法進行擴容操做,在容許的範圍上擴容爲原來的1.5倍安全

/**
     * 增長元素
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    /**
     * 確認容量
     */
    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
    /**
     * 計算容量
     * elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * 在這裏進行了初始化判斷
     * 最小容量爲10
     */
    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
    /**
     * 修改次數記錄modCount,容量是否擴容判斷
     */
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    /**
     * 擴容
     */
    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:
        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;
    }
    /**
     * 將element插入index的位置
     */    
    public void add(int index, E element) {
        rangeCheckForAdd(index);
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        // native方法實現拷貝
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

addAll

/**
     * 先對集合容量進行檢查,記錄修改次數,調用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;
    }
    /**
     * 和上邊不一樣之處在於將數組拷貝到新數組index位置,其後元素依次排序
     */    
    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;
    }

clear

/**
     * 清空
     */ 
    public void clear() {
        modCount++;

        // clear to let GC do its work
        // 註釋上也寫明瞭緣由,置空爲了讓GC工做,回收空間
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

contains

/**
     * 判斷某個元素是否在集合中
     */ 
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
    /**
     * 返回元素在集合中的首個索引(從小到大)
     * 主要是判空區分
     */     
    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;
    }

get

/**
     * 獲取索引爲index的元素,先檢查索引值,再調用elementData方法
     */
    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

iterator

/**
     * 返回迭代器 內部類實現
     */
    public Iterator<E> iterator() {
        return new Itr();
    }
    
    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        Itr() {}

        public boolean hasNext() {
            return cursor != size;
        }
        /**
         * 獲取索引爲cursor的元素,並置cursor = cursor + 1,方便下次調用,lastRet記錄當前返回的元素索引
         */
        @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];
        }
        /**
         * 移除當前lastRet對應元素,cursor置爲lastRet,修改次數修改
         */
        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();
            }
        }
        /**
         * jdk 1.8新增接口,調用accept接口對每一個元素執行動做
         */
        @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();
        }
    }

lastIndexOf

/**
     * 返回匹配對象的首個索引(從大到小)
     */
    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;
    }

remove

/**
     * 刪除索引爲index的元素
     */
    public E remove(int index) {
        rangeCheck(index);
        //修改記錄+1
        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            //使用arraycopy從新整理集合
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to 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) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

removeAll

/**
     * 移除全部和參數集合相同的元素
     */
    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }
    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++)
                //將保留的數據寫回elementData
                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) {
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    //清理爲空的數據
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }

set

/**
     * 設置索引爲index的值爲element
     */
    public E set(int index, E element) {
        rangeCheck(index);

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

toArray

/**
     * 將list元素拷貝返回
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

subList

/**
     * 獲取子數組,內部類實現,子數組只是引用了原來的數組,所以改變子數組,至關於改變了原來的數組
     * 子數組再也不詳細說明,ArrayList類類似,只是多了幾個成員變量,來限制範圍
     * 源碼部分自行查看
     */
    public List<E> subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, 0, fromIndex, toIndex);
    }

總結

總體來看ArrayList源碼仍是比較簡單的,從源碼部分也能注意到幾個點:併發

  • ArrayList是基於數組實現的集合類
  • Object數組能夠存放null
  • 非線程安全,如需併發線程安全類需使用對應的線程安全包裝類保證
  • 如已經肯定容量大小,能夠提早初始化設置好對應容量以減小中間擴容帶來的損耗

總的來講,仍是相對比較簡單了,但願對各位有所幫助,若有錯誤,歡迎指正,謝謝dom

相關文章
相關標籤/搜索