ArrayList類源碼閱讀

一、簡介

ArrayList 位於java.util包中,使我們經常使用到的一個集合對象。

  • ArrayList是可調整大小的數組列表接口。實現所有可選的列表操作,並允許所有元素,元素也可以重複,包括null;
  • 除了實現List接口外,這個類還提供了操作數組大小的方法,該數組在內部用於存儲列表;
  • ArrayList類似Vector,只是是非同步的;
  • 當元素被添加到ArrayList中時,容量自動增長(自動擴容機制)
  • 防止意外對列表的非同步訪問: List list = Collections.synchronizedList(new ArrayList(...));
  •  
  • ArrayList繼承了AbstractList<E>抽象類,實現了 List<E>, RandomAccess隨機訪問接口 ,Cloneable克隆接口, java.io.Serializable序列化接口;
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
    
}
  • 初始容量大小 
//初始容量爲10
private static final int DEFAULT_CAPACITY = 10;
//空數組,在用戶指定容量爲 0 時返回
private static final Object[] EMPTY_ELEMENTDATA = {};
//空數組,默認返回
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

//對象數組,集合元素存放在該數組中。用於非私有以簡化嵌套類訪問
//ArrayList基於數組實現,用該數組保存數據,
//ArrayList 的容量就是該數組的長度
transient Object[] elementData; // non-private to simplify nested class access
//ArrayList實際存儲的數據數量
private int size;
  • 構造方法
//構造具有指定初始容量的空列表。
public ArrayList(int initialCapacity) {
    if (initialCapacity > 0) {
        //直接new一個指定容量的對象數組
        this.elementData = new Object[initialCapacity];
    } else if (initialCapacity == 0) {
        //空對象數組
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        //如果initialCapacity < 0則拋出異常
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
}

//構造一個初始容量爲10的空列表。
//當元素第一次被加入時,擴容至默認容量 10
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

//根據集合對象構造ArrayList集合
public ArrayList(Collection<? extends E> c) {
    //將集合對象轉換爲對象數組
    elementData = c.toArray();
    //把轉化後的Object[]數組長度賦值給當前ArrayList的size,並判斷是否爲0
    if ((size = elementData.length) != 0) {
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        //判斷是否是對象數組類型
        if (elementData.getClass() != Object[].class)
           //如果不是Object[]類型,則轉換爲Object[]類型
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    } else {
        // replace with empty array.
        this.elementData = EMPTY_ELEMENTDATA;
    }
}
  • 自動擴容
//自動擴容
public void ensureCapacity(int minCapacity) {
    //計算最小擴充的容量
    int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
        // 判斷是不是空的ArrayList,如果是空則最小擴充容量爲10,否則最小擴充量爲0
        ? 0
        // 默認擴充容量爲10
        : DEFAULT_CAPACITY;

    // 若用戶指定的最小容量 > 最小擴充的容量,則以用戶指定的爲準
    if (minCapacity > minExpand) {
        ensureExplicitCapacity(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++;

    // 防止溢出代碼:確保指定的最小容量 > 數組緩衝區當前的長度
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

//數組緩衝區最大存儲容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

//增加容量(擴容),以確保它至少可以容納由最小容量參數minCapacity指定的元素數量
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    //新容量 = 舊容量 + (舊容量 / 2)
    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
        //OutOfMemoryError內存溢出
        throw new OutOfMemoryError();
        //最大容量分配爲:Integer.MAX_VALUE
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

二、常用API:

【a】size()、isEmpty()、contains()、indexOf()、lastIndexOf()

//返回ArrayList實際存儲的元素數量
public int size() {
    return size;
}

//判斷元素是否爲空
public boolean isEmpty() {
    //實際上判斷長度是否等於0
    return size == 0;
}

//判斷是否包含某個元素
public boolean contains(Object o) {
    //根據indexOf()來實現,下標>=0表示存在,-1表示否則不存在
    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++)
        //正序循環遍歷elementData對象數組,一個一個比較
            if (o.equals(elementData[i]))
                return i;
    }
    return -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--)
         //倒序循環遍歷elementData對象數組,一個一個比較
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

【b】clone()、toArray()

//返回此ArrayList實例的淺拷貝。(不會複製元素本身。)
public Object clone() {
    try {
        ArrayList<?> v = (ArrayList<?>) super.clone();
        v.elementData = Arrays.copyOf(elementData, size);
        v.modCount = 0;
        return v;
    } catch (CloneNotSupportedException e) {
        // this shouldn't happen, since we are Cloneable
        throw new InternalError(e);
    }
}

//返回一個包含列表中所有元素的數組,返回新的對象數組
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;
}

【c】elementData()

//根據下標,返回集合中某個元素
@SuppressWarnings("unchecked")
E elementData(int index) {
    return (E) elementData[index];
}

//根據下標,返回集合中某個元素
public E get(int index) {
    //首先檢查下標是否越界
    rangeCheck(index);
    //根據下標返回數組對應下標的元素
    return elementData(index);
}

//檢查給定的索引是否在範圍內
private void rangeCheck(int index) {
    if (index >= size)
    //拋出IndexOutOfBoundsException數組越界異常
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

【d】set()

//將此列表中指定位置的元素替換爲指定的元素
public E set(int index, E element) {
    //首先檢查下標是否越界
    rangeCheck(index);
    //獲取舊下標對應的值
    E oldValue = elementData(index);
    //更新數組中對應下標的值爲element
    elementData[index] = element;
    //返回更新前的值
    return oldValue;
}

【e】add()

//將指定的元素追加到此列表的末尾
public boolean add(E e) {
    //擴容
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    //增加size,然後新增一個數組元素,下標爲(size + 1)
    elementData[size++] = e;
    return true;
}

//擴容操作
private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }

    ensureExplicitCapacity(minCapacity);
}

//將指定元素插入其中的指定位置列表。
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長度加1
    size++;
}

private void rangeCheckForAdd(int index) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

我們通過簡單的代碼分析一下自動擴容的流程:

List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
list.add("8");
list.add("9");
list.add("10");
//添加到11這個元素的時候開始擴容
//minCapacity = 11 此時elementData.length=10 ,由於11>10達到擴容條件,進入grow()進行擴容
// 新容量 = 舊容量 + (舊容量 / 2) = 10 + (10 / 2) = 15
list.add("11");
System.out.println(list);
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

【f】remove()

//刪除列表中指定位置的元素
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);
    //將最後一個元素置空,方便GC垃圾回收
    elementData[--size] = null; // clear to let GC do its work
    //返回刪除後的元素值
    return oldValue;
}

//從列表中刪除指定元素的第一個匹配項,如果它存在。如果列表不包含該元素,則不變
public boolean remove(Object o) {
    if (o == null) {
        //循環判斷數組元素,挨個判斷是否爲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);
     //將最後一個元素置空,方便GC垃圾回收                    
    elementData[--size] = null; // clear to let GC do its work
}

【g】clear()

//從列表中刪除所有元素。將列表調用返回後爲空。
//將數組緩衝區所以元素置爲null
public void clear() {
    modCount++;

    // clear to let GC do its work
    for (int i = 0; i < size; i++)
    //將數組每個元素都置爲null,方便GC垃圾回收
        elementData[i] = null;
    //更新長度爲0
    size = 0;
}

【h】addAll()

//將指定集合中的所有元素追加到列表中
//ArrayList 是線程不安全的,如果同時有兩個線程,一個線程向list中新增元素,一個線程修改list中元素,可能會存在線程安全問題
public boolean addAll(Collection<? extends E> c) {
    //將集合對象轉換爲對象數組
    Object[] a = c.toArray();
    //需要增加的元素的個數
    int numNew = a.length;
    //擴容,增量modCount
    ensureCapacityInternal(size + numNew);  // Increments modCount
    //數組拷貝,將需要添加的對象數組拷貝到elementData中
    System.arraycopy(a, 0, elementData, size, numNew);
   //更新size
    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);
    //拷貝下標從0至index下標的元素
    System.arraycopy(a, 0, elementData, index, numNew);
    //更新size
    size += numNew;
    return numNew != 0;
}

【i】removeRange()

//從該列表中刪除其索引位於之間的所有元素,將後面的元素往前面移動
//需要將toIndex之後(包括toIndex)的元素都向前移動(toIndex-fromIndex)個位置
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++) {
        //將刪除之後的元素置空,方便GC垃圾回收         
        elementData[i] = null;
    }
    size = newSize;
}

詳細可以參考下圖debug:System.arraycopy數組拷貝後:

【j】removeAll()

//元素中包含的所有元素從該列表中移除指定的集合。
public boolean removeAll(Collection<?> c) {
    //判斷是否爲null,如果爲null拋出NullPointerException空指針異常
    Objects.requireNonNull(c);
    return batchRemove(c, false);
}

//從這個列表中刪除所有不包含在指定集合中的元素。
public boolean retainAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, true);
}

//批量移除集合元素
//complement: 是否是補集
//complement: true:移除list中除了c集合中的所有元素;
//complement: false:移除list中c集合中的元素;
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) {
            // 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;
}

【k】writeObject()、readObject()

//將ArrayList實例的狀態保存到流中is,序列化它
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 size as capacity for behavioural compatibility with clone()
    s.writeInt(size);

    // 以合適的順序寫入所有的元素
    for (int i=0; i<size; i++) {
        s.writeObject(elementData[i]);
    }

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

//從流中反序列化重新構造ArrayList實例
private void readObject(java.io.ObjectInputStream s)
    throws java.io.IOException, ClassNotFoundException {
    elementData = EMPTY_ELEMENTDATA;

    // Read in size, and any hidden stuff
    s.defaultReadObject();

    // Read in capacity
    s.readInt(); // ignored

    if (size > 0) {
        // be like clone(), allocate array based upon size not capacity
        //就像clone(),根據大小而不是容量來分配數組
        ensureCapacityInternal(size);

        Object[] a = elementData;
        // Read in all elements in the proper order.
        //按適當的順序讀取所有的元素
        for (int i=0; i<size; i++) {
            a[i] = s.readObject();
        }
    }
}

【l】iterator()

//適當的順序對列表中的元素返回一個迭代器。
public Iterator<E> iterator() {
    return new Itr();
}

//Itr是私有內部類
private class Itr implements Iterator<E> {
    //遊標,下一個要返回的元素的索引
    int cursor;       // index of next element to return
   //最後一個返回元素的索引;-1如沒有
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    //判斷是否還有下一個元素
    public boolean hasNext() {
        //即判斷遊標是否到了list的最大長度
        return cursor != size;
    }

    //返回下一個元素
    @SuppressWarnings("unchecked")
    public E next() {
        checkForComodification();
        //i爲遊標,即當前元素的索引
        int i = cursor;
        if (i >= size)
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)
        //檢查list中數量是否發生變化
            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;
            //將最後一個元素返回的索引重置爲-1
            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() {
        //在迭代list集合時元素數量發生變化時會造成modCount和expectedModCount不相等
        //當expectedModCount和modCount不相等時,就拋出ConcurrentModificationException
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

【m】sort()

//排序,可以傳入比較器接口實現自定義排序
@Override
@SuppressWarnings("unchecked")
public void sort(Comparator<? super E> c) {
    final int expectedModCount = modCount;
    //底層根據Arrays.sort()實現
    Arrays.sort((E[]) elementData, 0, size, c);
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    modCount++;
}

ArrayList底層實際上都是在操作對象數組來完成的,用的比較多的就是數組的拷貝System.arraycopy:

public static native void arraycopy(Object src,  int  srcPos,
                                    Object dest, int destPos,
                                    int length);
其中:src表示源數組,srcPos表示源數組要複製的起始位置,desc表示目標數組,length表示要複製的長度。

示例:

int[] sourceArr = {1, 2, 3};
int[] targetArr = {4, 5, 6};
System.arraycopy(sourceArr, 0, targetArr, 0, sourceArr.length);
for (int i : sourceArr) {
    System.out.print(i + " ");
}
System.out.println();
for (int j : targetArr) {
    System.out.print(j + " ");
}

 

發佈了206 篇原創文章 · 獲贊 89 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章