arrayList淺析

linkedList,之後再說java

概述

arrayList是基於數組的。當知道數組的下標時,查找很快,當你不關心要插入的地方是否有值時,插入也很快。但數組大小有限,不易擴展,因此有了arrayList。(比hashMap簡單得多,畢竟一個是純鏈表(高級數組),一個是數組、鏈表、紅黑樹的組合)數組

屬性

/**
 * Default initial capacity.
 */
private static final int DEFAULT_CAPACITY = 10;//默認初始大小  10

/**
 * Shared empty array instance used for empty instances.
 */
private static final Object[] EMPTY_ELEMENTDATA = {};//指定初始化大小爲0時的數組,靜態全局,避免每次都建立

/**
 * 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 = {};//未設置初始大小時的數組

/**
 * 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;

方法

    構造方法安全

/**
     * 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];//在構造時,就初始化數組,hashMap是在put時才初始化
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;//空數組
    }

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

  add方法,太簡單,不值得細講函數

public boolean add(E e) {//純粹的插在最後,不具有修改的語義
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}
private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {//調用了無參構造函數
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);//單線程下,minCapacity最終爲10,ArrayList非線程安全
    }

    ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
    modCount++;//不要在for(? : ?List)循環裏修改,會有異常。可用迭代器、CORList代替

    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);//新容量約爲原來的1.5倍(擴容一半)
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)             //MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
}

大底上add,remove,最後都會調用System.array...(....),比較簡單。arrayList的底層畢竟是數組,因此不會太複雜。性能

有一點要注意,批量刪除時,從尾部開始刪ui

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);//性能消耗的關鍵在於此,刪除一個元素時,爲了保持數組的連續,要對數組進行移動
                                       //舉兩個極端的例子,listA每次remove(0),要移動size-1個元素; listB每次remove(size-1),移動0個元素
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }
相關文章
相關標籤/搜索