ArrayList實現原理

概述

ArrayList能夠簡單的看做是動態數組,相對於普通的數組它能夠動態的增長容量或者減小容量。要注意的是ArrayList並非線程安全的,所以通常建議在單線程中使用ArrayList。java

實現原理

繼承關係

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable

ArrayList繼承AbstractList實現List, RandomAccess, Cloneable, java.io.Serializable接口數組

關鍵屬性

/**
     * 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.
     */
    // 數據的數組
    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;

底層使用數組保存全部元素
transient 若是用transient聲明一個實例變量,當對象存儲時,它的值不須要維持。換句話來講就是,用transient關鍵字標記的成員變量不參與序列化過程安全

構造方法

/**
     * 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.
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

默認狀況下初始化空數組(長度爲0的數組)app

/**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] 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) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

指定數組的初始容量
當指定的初始容量大於0,初始化指定大小的數組
當指定的初始容量等於0,初始化空數組
當指定的初始容量小於0,拋出IllegalArgumentException異常dom

/**
     * 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) {
        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;
        }
    }

初始化指定集合的數組
當指定集合不爲空即長度不爲0,則複製該集合,不然初始化一個空數組ide

E get(int index) 獲取index位置的元素

// Positional Access Operations
    // 返回index下標的元素且強制轉化爲E(List<E>中的E)類型
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    /**
     * 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) {
        // 檢查index是否越界
        rangeCheck(index);
        // 返回index下標的元素
        return elementData(index);
    }

    /**
     * Checks if the given index is in range.  If not, throws an appropriate
     * runtime exception.  This method does *not* check if the index is
     * negative: It is always used immediately prior to an array access,
     * which throws an ArrayIndexOutOfBoundsException if index is negative.
     */
    private void rangeCheck(int index) {
        // 檢查index是否大於等於size(數組的元素數量),由於數組下標從0開始計算,因此也不能等於元素數量
        // 這裏沒有檢查index < 0的狀況,由於index < 0時數組會自動拋出異常,因此並未檢查index<0的狀況
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * Constructs an IndexOutOfBoundsException detail message.
     * Of the many possible refactorings of the error handling code,
     * this "outlining" performs best with both server and client VMs.
     */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

首先判斷index是否越界,這裏並無判斷是否小於0,由於下標小於0時數組會拋出異常。越界則拋出IndexOutOfBoundsException異常,反之返回數組對應index位置的元素ui

E set(int index, E element) 設置(覆蓋)index位置的元素

/**
     * Replaces the element at the specified position in this list with
     * the specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        rangeCheck(index);

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

和get同樣先判斷index(下標)是否越界,不越界則先獲取原來index位置上的元素,接着設置(覆蓋)index位置上的元素,而後返回原來的元素,反之拋出IndexOutOfBoundsException異常this

boolean add(E e) 添加一個元素到列表尾

/**
     * 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;
        // size += 1;
        elementData[size++] = e;
        return true;
    }

    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;  // 默認容量爲10

    // 若是數據等於默認數據,返回默認容量和minCapacity(所需容量最小值)的最大值,反之返回所需容量最小值
    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }

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

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;  // 操做數+1

        // 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;  // 數組最大容量爲Integer最大值-8

    /**
     * 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;
        // 若是新的容量大於數組最大容量,再調用hugeCapacity計算新的容量
        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();
        // 大於數組最大容量返回Integer最大值,反之返回數組最大容量
        return (minCapacity > MAX_ARRAY_SIZE) ?
                Integer.MAX_VALUE :
                MAX_ARRAY_SIZE;
    }

添加一個元素到列表尾,當列表容量不足時自動擴容(一般是擴容至原來的1.5倍),添加成功返回truespa

void add(int index, E element) 在index處放置元素

/**
     * 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!!
        // 將elementData從index開始後面的元素日後移一位
        System.arraycopy(elementData, index, elementData, index + 1,
                size - index);
        elementData[index] = element;
        size++;
    }

    /**
     * A version of rangeCheck used by add and addAll.
     */
    private void rangeCheckForAdd(int index) {
        // 當index等於size時至關於添加元素到列表尾
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

將elementData數組從index開始後面的元素日後移一位,接着在index處放置元素
模擬添加數據(lierabbit)到index=4過程以下
clipboard.png線程

boolean addAll(Collection<? extends E> c) 添加一個集合裏的全部元素到列表尾

/**
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the
     * specified collection's Iterator.  The behavior of this operation is
     * undefined if the specified collection is modified while the operation
     * is in progress.  (This implies that the behavior of this call is
     * undefined if the specified collection is this list, and this
     * list is nonempty.)
     *
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        // 檢查當前容量是否還能夠在容納a數組的元素,不夠則擴容
        ensureCapacityInternal(size + numNew);  // Increments modCount
        // 將a數組裏的元素添加到elementData末尾
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        // a數組不爲空(長度不爲0)時返回true,反之false
        return numNew != 0;
    }

將要添加的集合變爲數組,而後將其複製到elementData數組末尾

boolean addAll(int index, Collection<? extends E> c) 添加一個集合裏的全部元素到index位置

/**
     * Inserts all of the elements in the specified collection into this
     * list, starting at the specified position.  Shifts the element
     * currently at that position (if any) and any subsequent elements to
     * the right (increases their indices).  The new elements will appear
     * in the list in the order that they are returned by the
     * specified collection's iterator.
     *
     * @param index index at which to insert the first element from the
     *              specified collection
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        // 檢查下標是否越界
        rangeCheckForAdd(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        // 檢查當前容量是否還能夠在容納a數組的元素,不夠則擴容
        ensureCapacityInternal(size + numNew);  // Increments modCount

        // 須要日後移動幾個位置
        int numMoved = size - index;
        if (numMoved > 0)
            // 從index開始,日後的元素向後移動numMoved個位置
            System.arraycopy(elementData, index, elementData, index + numNew,
                    numMoved);
        // 將a數組裏的全部元素複製到elementData從index到index + numNew -1的位置上
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        // a數組不爲空(長度不爲0)時返回true,反之false
        return numNew != 0;
    }

將要添加的集合變爲數組,而後把elementData數組從index開始,日後的元素向後移動numMoved個位置,接着將要添加的數組裏的全部元素複製到elementData從index到index + numNew -1的位置上

void trimToSize() 改變列表內部數組容量至列表實際元素數量

/**
     * Trims the capacity of this <tt>ArrayList</tt> instance to be the
     * list's current size.  An application can use this operation to minimize
     * the storage of an <tt>ArrayList</tt> instance.
     */
    public void trimToSize() {
        modCount++;  // 操做數+1
        // 若是數組實際元素數量小於數組長度
        if (size < elementData.length) {
            // 若是數組實際元素數量等於0則數組被賦值爲空數組,反之建立一個新的元素數量等於數組長度的數組
            elementData = (size == 0)
                    ? EMPTY_ELEMENTDATA
                    : Arrays.copyOf(elementData, size);
        }
    }

當數據穩定了以後可使用這個方法來減小內存的使用

int indexOf(Object o) 查找o元素在列表第一次出現的位置

/**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     */
    public int indexOf(Object o) {
        //元素能夠爲null,若是爲null返回null的下標
        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;
        }
        // 沒有找到對應的元素返回-1
        return -1;
    }

ArrayList中能夠存放null元素,indexof是返回elementData數組中值相同的首個元素的下標,indexof中比較方法是equals而equals是比較元素的值,所以必須對null單獨查找。若是未找到該元素則返回-1

E remove(int index) 刪除index位置上的元素

/**
     * 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++;  // 操做數+1
        E oldValue = elementData(index);  // 獲取index位置上的元素

        int numMoved = size - index - 1;  // 須要往前移動幾個位置
        if (numMoved > 0)
            // 從index + 1開始,日後的元素向前移動1個位置
            System.arraycopy(elementData, index+1, elementData, index,
                    numMoved);
        // 將數組末尾元素置空
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

模擬刪除index=4(值爲lierabbit)過程以下
clipboard.png

boolean remove(Object o) 刪除o元素

/**
     * 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) {
        // 元素能夠爲null,分開搜索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;
                }
        }
        // 沒有找到返回false
        return false;
    }

    /*
     * Private remove method that skips bounds checking and does not
     * return the value removed.
     */
    // 因爲已經找到元素,則元素一定存在,則index一定合理,因此不須要在檢查index是否越界
    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
    }

經過尋找o元素,能夠得到其下標,再根據下標刪除o元素

forEach(Consumer<? super E> action)遍歷列表

/**
     * The number of times this list has been <i>structurally modified</i>.
     * Structural modifications are those that change the size of the
     * list, or otherwise perturb it in such a fashion that iterations in
     * progress may yield incorrect results.
     *
     * <p>This field is used by the iterator and list iterator implementation
     * returned by the {@code iterator} and {@code listIterator} methods.
     * If the value of this field changes unexpectedly, the iterator (or list
     * iterator) will throw a {@code ConcurrentModificationException} in
     * response to the {@code next}, {@code remove}, {@code previous},
     * {@code set} or {@code add} operations.  This provides
     * <i>fail-fast</i> behavior, rather than non-deterministic behavior in
     * the face of concurrent modification during iteration.
     *
     * <p><b>Use of this field by subclasses is optional.</b> If a subclass
     * wishes to provide fail-fast iterators (and list iterators), then it
     * merely has to increment this field in its {@code add(int, E)} and
     * {@code remove(int)} methods (and any other methods that it overrides
     * that result in structural modifications to the list).  A single call to
     * {@code add(int, E)} or {@code remove(int)} must add no more than
     * one to this field, or the iterators (and list iterators) will throw
     * bogus {@code ConcurrentModificationExceptions}.  If an implementation
     * does not wish to provide fail-fast iterators, this field may be
     * ignored.
     */
    protected transient int modCount = 0;//操做數

    @Override
    public void forEach(Consumer<? super E> action) {
        // 確保不爲空
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    /**
     * Checks that the specified object reference is not {@code null}. This
     * method is designed primarily for doing parameter validation in methods
     * and constructors, as demonstrated below:
     * <blockquote><pre>
     * public Foo(Bar bar) {
     *     this.bar = Objects.requireNonNull(bar);
     * }
     * </pre></blockquote>
     *
     * @param obj the object reference to check for nullity
     * @param <T> the type of the reference
     * @return {@code obj} if not {@code null}
     * @throws NullPointerException if {@code obj} is {@code null}
     */
    public static <T> T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }

這裏能夠看到modCount的用處,當modCount發生改變後,馬上拋出ConcurrentModificationException異常。經過以前的分析能夠知道當列表內容被修改時modCount會增長。也就是說若是在遍歷ArrayList的過程當中有其餘線程修改了ArrayList,那麼將拋出ConcurrentModificationException異常

ArrayList小結

  • ArrayList是List接口的一個可變大小的數組的實現
  • ArrayList的內部是使用一個Object對象數組來存儲元素的
  • 初始化ArrayList的時候,能夠指定初始化容量的大小,若是不指定,就會使用默認大小,爲10
  • 當添加一個新元素的時候,首先會檢查容量是否足夠添加這個元素,若是夠就直接添加,若是不夠就進行擴容,擴容爲原數組容量的1.5倍
  • 當在index處放置一個元素的時候,會將數組index處右邊的元素所有右移
  • 當在index處刪除一個元素的時候,會將數組index處右邊的元素所有左移
本文首發: https://lierabbit.cn/2018/01/...
相關文章
相關標籤/搜索