Java.util.*中集合之ArrayList源碼分析

Java.util.*中集合之ArrayList源碼分析

一、ArrayList簡介

ArrayList是可以動態增長和縮減的索引序列,它是基於數組實現的List類。

該類封裝了一個動態再分配的Object[]數組,每一個類對象都有一個capacity屬性,表示它們所封裝的Object[]數組的長度,當向ArrayList中添加元素時,該屬性值會自動增加。如果想ArrayList中添加大量元素,可使用ensureCapacity方法一次性增加capacity,可以減少增加重分配的次數提高性能。

ArrayList的用法和Vector向類似,但是Vector是一個較老的集合,具有很多缺點,不建議使用。另外,ArrayList和Vector的區別是:ArrayList是線程不安全的,當多條線程訪問同一個ArrayList集合時,程序需要手動保證該集合的同步性,而Vector則是線程安全的。

ArrayList與Collection關係如下圖:

二、ArrayList源碼分析

下面就ArrayList的源代碼進行簡單的分析:

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;
    //默認的初始容量爲10
    private static final int DEFAULT_CAPACITY = 10;
    private static final Object[] EMPTY_ELEMENTDATA = {};
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    transient Object[] elementData; 
    // ArrayList中實際數據的數量
    private int size;
    public ArrayList(int initialCapacity) //帶初始容量大小的構造函數
    {
        if (initialCapacity > 0)   //初始容量大於0,實例化數組
        {
            this.elementData = new Object[initialCapacity];
        } 
        else if (initialCapacity == 0) //初始化等於0,將空數組賦給elementData
        {
            this.elementData = EMPTY_ELEMENTDATA;  
        } 
        else    //初始容量小於,拋異常
        {
            throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
        }
    }
    public ArrayList()  //無參構造函數,默認容量爲10
    {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
    public ArrayList(Collection<? extends E> c)  //創建一個包含collection的ArrayList
    {
        elementData = c.toArray(); //返回包含c所有元素的數組
        if ((size = elementData.length) != 0)
        {
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);//複製指定數組,使elementData具有指定長度
        } 
        else
        {
            //c中沒有元素
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
    //將當前容量值設爲當前實際元素大小
    public void trimToSize()
    {
        modCount++;
        if (size < elementData.length) 
        {
            elementData = (size == 0)? EMPTY_ELEMENTDATA:Arrays.copyOf(elementData, size);
        }
    }
    
    //將集合的capacit增加minCapacity
    public void ensureCapacity(int minCapacity) 
    {
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)?0: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;
    private void grow(int minCapacity)
    {
        int oldCapacity = elementData.length;
     //注意此處擴充capacity的方式是將其向右一位再加上原來的數,實際上是擴充了1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
    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的大小
    public int size()
    {
        return size;
    }
    //判斷ArrayList是否爲空
    public boolean isEmpty() {
        return size == 0;
    }
    //判斷ArrayList中是否包含Object(o)
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
    //正向查找,返回ArrayList中元素Object(o)的索引位置
    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++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
    //逆向查找,返回返回ArrayList中元素Object(o)的索引位置
    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--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
    //返回此 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);
        }
    }
    //返回一個包含ArrayList中所有元素的數組
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[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;
    }
    
    //將指定的元素添加到此列表的尾部
    public boolean add(E e) 
    {
        ensureCapacityInternal(size + 1);  
        elementData[size++] = e;
        return true;
    }
    
    // 將element添加到ArrayList的指定位置   
    public void add(int index, E element) {
        rangeCheckForAdd(index);
        ensureCapacityInternal(size + 1); 
       
        //從指定源數組中複製一個數組,複製從指定的位置開始,到目標數組的指定位置結束。
        //arraycopy(被複制的數組, 從第幾個元素開始複製, 要複製到的數組, 從第幾個元素開始粘貼, 一共需要複製的元素個數)
        //即在數組elementData從index位置開始,複製到index+1位置,共複製size-index個元素
        System.arraycopy(elementData, index, elementData, index + 1,size - index);
        elementData[index] = element;
        size++;
    }
    
    //刪除ArrayList指定位置的元素  
    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; //將原數組最後一個位置置爲null
        return oldValue;
    }
    
    //移除ArrayList中首次出現的指定元素(如果存在)。
    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; 
    }
   
    //清空ArrayList,將全部的元素設爲null
    public void clear() 
    {
        modCount++;
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        size = 0;
    }
    
    //按照c的迭代器所返回的元素順序,將c中的所有元素添加到此列表的尾部
    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;
    }
    
    //從指定位置index開始,將指定c中的所有元素插入到此列表中
    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)
            //先將ArrayList中從index開始的numMoved個元素移動到起始位置爲index+numNew的後面去
            System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
        //再將c中的numNew個元素複製到起始位置爲index的存儲空間中去
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }
    
    //刪除fromIndex到toIndex之間的全部元素
    protected void removeRange(int fromIndex, int toIndex)
    {
        modCount++;
        //numMoved爲刪除索引後面的元素個數
        int numMoved = size - toIndex;  
        //將刪除索引後面的元素複製到以fromIndex爲起始位置的存儲空間中去
        System.arraycopy(elementData, toIndex, elementData, fromIndex,numMoved);
        int newSize = size - (toIndex-fromIndex);
        //將ArrayList後面(toIndex-fromIndex)個元素置爲null
        for (int i = newSize; i < size; i++)
        {
            elementData[i] = null;
        }
        size = newSize;
    }
    
    //檢查索引是否越界
    private void rangeCheck(int index)
    {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    private void rangeCheckForAdd(int index) 
    {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }
    
    //刪除ArrayList中包含在c中的元素
    public boolean removeAll(Collection<?> c)
    {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }
    
    //刪除ArrayList中除包含在c中的元素,和removeAll相反
    public boolean retainAll(Collection<?> c) 
    {
        Objects.requireNonNull(c);  //檢查指定對象是否爲空
        return batchRemove(c, true);
    }
    
    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)  //判斷c中是否有elementData[r]元素

                    elementData[w++] = elementData[r];
        }
        finally 
        {
            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;
    }
    
    //將ArrayList的“容量,所有的元素值”都寫入到輸出流中 
    private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException
    {
        int expectedModCount = modCount;
        s.defaultWriteObject();
        //寫入數組大小
        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;
        s.defaultReadObject();
        s.readInt(); // ignored
        if (size > 0) {
            // be like clone(), allocate array based upon size not capacity
            ensureCapacityInternal(size);
            Object[] a = elementData;
            // Read in all elements in the proper order.
            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }

三、ArrayList遍歷方式

ArrayList支持3種遍歷方式

1、通過迭代器遍歷:

    Iterator iter = list.iterator();
    while (iter.hasNext())
    {
        System.out.println(iter.next());
    } 

2、隨機訪問,通過索引值去遍歷,由於ArrayList實現了RandomAccess接口

int size = list.size();
for (int i=0; i<size; i++) 
{
    System.out.println(list.get(i));        
}        

3、for循環遍歷:

for(String str:list)
{
    System.out.println(str);
}    
public class DemoMain 
{
    public static void main(String[] args)
    {
        List<String> list=new ArrayList<String>();
        list.add("nihao");
        list.add("xujian");
        list.add("wang");
        System.out.println("--------通過迭代器遍歷---------");
        Iterator iter = list.iterator();
        while (iter.hasNext())
        {
           System.out.println(iter.next());
        }
        
        System.out.println("--------通過隨機訪問---------");
        int size = list.size();
        for (int i=0; i<size; i++) 
        {
            System.out.println(list.get(i));        
        }
        
        System.out.println("--------通過for循環訪問---------");
        for(String str:list)
        {
            System.out.println(str);
        }
    }
}

運行結果如圖示:
在這裏插入圖片描述

轉載地址: https://www.cnblogs.com/xujian2014/p/4625346.html

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