JDK源碼閱讀——ArrayList(1)

作爲Java集合框架下的一個重要的類,ArrayList類繼承了AbstractList類,並擴展了List, RandomAccess, Cloneable, java.io.Serializable等接口。ArrayList的成員變量主要有三個數組:

private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
transient Object[] elementData; // non-private to simplify nested class access

elementData肯定是用來存儲元素的,那前兩個static數組是做什麼的呢?我們來看下ArrayList的構造方法:

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);
    }
}
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)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    } else {
        // replace with empty array.
        this.elementData = EMPTY_ELEMENTDATA;
    }
}

ArrayList有三種構造方法,默認構造方法將DEFAULTCAPACITY_EMPTY_ELEMENTDATA數組賦值給elementData;int initialCapacity作爲參數的構造方法創建一個大小爲initialCapacity的數組,若initialCapacity == 0,則將EMPTY_ELEMENTDATA賦值給elementData;以Collection c作爲參數的構造方法判斷c.toArray的長度是否爲0,是則將EMPTY_ELEMENTDATA賦值給elementData,否則根據情況將c.toArray賦給elementData,或者使用Arrays.copyOf創建一個新數組

get和set方法首先對傳入的index參數進行檢查是否越界,再對數組的index位置取值或賦值:

public E get(int index) {
    rangeCheck(index);
    return elementData(index);
}
public E set(int index, E element) {
    rangeCheck(index);
    E oldValue = elementData(index);
    elementData[index] = element;
    return oldValue;
}

add方法進行了重載,向數組末尾加入一個元素,或是向指定位置加入一個元素:

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

其中System.arraycopy的原型是public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) ,將src從srcPos起始的length位複製到dest的destPos位之後的連續空間

remove方法同樣進行了重載,以int index作爲參數時,調用System.arraycopy將index之後的元素向前挪一位;以Object o爲參數時,利用o.equals找到跟o相等的第一個元素,調用private方法fastRemove(int index),原理與第一種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);
    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
}

這裏產生了一個疑惑:既然fastRemove的代碼和remove(int index)的大部分代碼相同,爲何在remove中不直接調用fastRemove?是否是爲了提高效率而減少方法的調用?那爲何在第二種remove中不直接把代碼展開?

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