Java集合系列之ArrayList

繼承關(guān)系

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

RandomAccess

public interface RandomAccess {
}

一個空接口,起到一個標(biāo)記的作用,有此接口的集合,通過下標(biāo)來獲取元素的速度比Iterator遍歷器快

成員變量

1.默認(rèn)數(shù)組容量

private static final int DEFAULT_CAPACITY = 10;

2.默認(rèn)空數(shù)組

private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

3.底層數(shù)據(jù)結(jié)構(gòu)是數(shù)組

 transient Object[] elementData;

數(shù)組類型是object,transient表示該數(shù)組不能被序列化

4.數(shù)組中的元素個數(shù)

 private int size;

關(guān)鍵方法

1.構(gòu)造方法

//構(gòu)造方法1
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);
    }
}

//構(gòu)造方法2
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

//構(gòu)造方法3
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;
    }
}

構(gòu)造方法1
根據(jù)指定容量,創(chuàng)建一個對象數(shù)組

構(gòu)造方法2
初始化一個空對象數(shù)組

構(gòu)造方法3
創(chuàng)建一個和指定集合一樣的對象數(shù)組

2.添加元素

//在末尾添加元素
public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}


//在指定位置添加元素
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
    System.arraycopy(a, 0, elementData, size, numNew);
    size += numNew;
    return numNew != 0;
}

//在指定位置添加一個集合
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;
}

分析
在指定位置添加元素的時候會調(diào)用rangeCheckForAdd方法

//要求0<=index<=size,否則拋異常
private void rangeCheckForAdd(int index) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

無論是哪個add方法,都必調(diào)用ensureCapacityInternal方法

private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }

    ensureExplicitCapacity(minCapacity);
}

如果數(shù)組是空數(shù)組,則minCapacity==10,這就是為什么在調(diào)用ArrayList的空構(gòu)造方法時,默認(rèn)容量是10的原因了。

該方法會調(diào)用ensureExplicitCapacity方法

private void ensureExplicitCapacity(int minCapacity) {
    modCount++;

    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

modCount記錄ArrayList的修改次數(shù)

當(dāng)容量不能達(dá)到minCapacity時,會調(diào)用grow方法增加容量
這個minCapacity的值,對于add來說是size+1,對于addAll來說是size+要添加的集合的size

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

新的容量首先擴張為舊容量的1.5倍
如果擴充后的容量仍然小于minCapacity,則新的容量擴充為minCapacity
如果新的容量超過最大容量,則調(diào)用hugeCapacity方法

private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

從這里可以看出ArrayList的最大容易是 Integer.MAX_VALUE,而不是 Integer.MAX_VALUE-8

當(dāng)新的容量計算好之后,就之前的數(shù)組中的元素一一復(fù)制到新容量的數(shù)組里面。

3.數(shù)組擴容

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

我們知道數(shù)組在擴容過程中,需要數(shù)組的復(fù)制操作,這個挺耗時的,為了減少擴容的操作,可以直接調(diào)用該方法,直接指定數(shù)組的容量。但缺點就是浪費內(nèi)存。

4. 刪除元素

//刪除指定位置上的元素
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;
}

//刪除指定元素
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 boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, false);
}

public boolean retainAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, true);
}

//complement為ture,保留公共元素,為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++)
            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;
}

分析
刪除操作,會先計算出要刪除元素的位置,然后將該位置后面的元素統(tǒng)一像前移動一位,同時size-1
刪除操作不會改變數(shù)組的容量

5.修改,查詢元素

//修改指定位置的元素,并返回該位置之前的元素
public E set(int index, E element) {
    rangeCheck(index);

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

//根據(jù)下標(biāo)獲取元素
public E get(int index) {
    rangeCheck(index);

    return elementData(index);
}

其他方法就不一一說明了

總結(jié)

ArrayList是一個動態(tài)可擴容的數(shù)組
當(dāng)通過空構(gòu)造函數(shù)創(chuàng)建ArrayList時,默認(rèn)容量為10

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容