Java集合系列之ArrayList

Java集合系列之ArrayList

Hello,你們好,上一篇Java集合系列給你們講了HashMap,其實工做中,若是不設計到併發編程,HashMap和ArrayList用的是最多的,這一篇就給你們分享一下ArrayList,這個集合底層賊簡單。其實任何使用ArrayList的地方均可以使用數組代替,ArrayList能夠理解爲動態數組,它的容量能夠自動擴大,同時也暴露了API出來手動擴大。你們想想,你用數組的時候其實不是同樣嗎?有時手動的調用Arrays.copyOf或者System.arraycopy(),其實ArrayList底層也是這麼用的。呵呵,是否是so easy .好了,老套路,文章結構:java

  1. ArrayList 大致介紹
  2. ArrayList API
  3. ArrayList擴容

1. ArrayList 大致介紹

ArrayList確實是太簡答了,也沒個什麼好介紹的,哈哈,底層就是一個數組。而後實現 List 接口,它是一個數組隊列,提供了相關的添加、刪除、修改、遍歷等功能。編程

2. ArrayList API

說下API吧,直接上代碼,你們看下代碼裏面註釋了,太簡答了,須要注意的地方我會在源碼後面提一下:數組

構造方法

//默認數組長度爲10
public ArrayList() {
        this(10);
    }
//能夠指定數組初始長度
public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }
//能夠傳進來一個Collection,而後內部轉換成數組。
public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }
複製代碼

存儲數據

set(int index, E element):該方法首先調用rangeCheck(index)來校驗 index 變量是否超出數組範圍,超出則拋出異常。然後,取出原 index 位置的值,而且將新的 element 放入 Index 位置,返回 oldValue。併發

add(E e):該方法是將指定的元素添加到列表的尾部。當容量不足時,會調用 grow 方法增加容量。this

public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    private void ensureCapacityInternal(int minCapacity) {
        modCount++;
        // 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);
        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:
        //注意這裏擴容時使用的Arrays.copyOf
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
複製代碼

add(int index, E element):在 index 位置插入 element,注意這個不是覆蓋,會把後面的元素都向後靠一個位置。spa

addAll(Collection<? extends E> c) 和 addAll(int index, Collection<? extends E> c):將特定 Collection 中的元素添加到 Arraylist 末尾。設計

讀取

get(int index):略指針

3. ArrayList擴容

從上面介紹的向 ArrayList 中存儲元素的代碼中,咱們看到,每當向數組中添加元素時,都要去檢查添加後元素的個數是否會超出當前數組的長度,若是超出,數組將會進行擴容,以知足添加數據的需求。數組擴容有兩個方法,其中開發者能夠經過一個 public 的方法ensureCapacity(int minCapacity)來增長 ArrayList 的容量,而在存儲元素等操做過程當中,若是遇到容量不足,會調用priavte方法private void ensureCapacityInternal(int minCapacity)實現。code

public void ensureCapacity(int minCapacity) {
        if (minCapacity > 0)
            ensureCapacityInternal(minCapacity);
    }

    private void ensureCapacityInternal(int minCapacity) {
        modCount++;
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    /** * 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;
        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 倍(從int newCapacity = oldCapacity + (oldCapacity >> 1)這行代碼得出)。這種操做的代價是很高的,所以在實際使用時,咱們應該儘可能避免數組容量的擴張。當咱們可預知要保存的元素的多少時,要在構造 ArrayList 實例時,就指定其容量,以免數組擴容的發生。對象

其次,這裏給你們提一下這個擴容時使用到的Arrays.copyOf方法:

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }
複製代碼

說白了,幹了什麼事呢,根據newLength建立了一個數組,而後調用System.arraycopy把數據拷貝了過去。這個System.arraycopy又是個native方法,聽說速度很快,關於深拷貝仍是淺拷貝,我這裏不給你們作試驗了,直接作結論:

  • Arrays.copyOf 方法內部使用System.arraycopy
  • System.arraycopy是native方法。
  • System.arraycopy 從新建立了數組,在這一層面是深拷貝。可是數組內的元素是淺拷貝。說白了,若是old數組裏面有一個Student對象,拷貝到新數組裏實際上是一個指向這個對象的指針,只是把指針拷貝了過去。

結語

好了好了,這個ArrayList我實在不知道怎麼寫,感受沒什麼東西能夠寫,內部就是一個數組,而後新增的時候回自動調用Arrays.copyOf擴容。也能夠手動擴容。 Over,Have a good day !

相關文章
相關標籤/搜索