java--ArrayList源碼理解



public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;

<span style="color:#006600;"><strong>    /**
     * 底層實現爲Object數組,transient 的意思是在集合序列化時不包含數組對象
     */</strong></span>
    private transient Object[] elementData;

    /**
     * 
     *<span style="color:#006600;">私有屬性,由於現實集合的元素個數</span>
     * 
     */
    private int size;

    /**
     * <span style="color:#006600;">能夠指定集合大小的構造方法</span>
     */
    public ArrayList(int initialCapacity) {
	super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
	this.elementData = new Object[initialCapacity];
    }

    /**
     * <span style="color:#009900;">默認構造方法</span><span style="color:#006600;">,默認初始化容量爲10</span>
     */
    public ArrayList() {
	this(10);
    }

    /**
     *
     *<span style="color:#006600;">第三個構造方法則將提供的集合轉成數組返回給elementData(返回若不是Object[]將調用Arrays.copyOf方法將其轉爲Object[])。</span>
     */
    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);
    }

    /**
     * <span style="color:#006600;">如果數組的長度大於集合的大小,則將集合的長度設置爲size</span>
     */
    public void trimToSize() {
	modCount++;
	int oldCapacity = elementData.length;
	if (size < oldCapacity) {
            elementData = Arrays.copyOf(elementData, size);
	}
    }

    /**
     * 
     * <span style="color:#006600;">擴容函數,當想集合中添加元素時會先檢查數據容量,如果容量滿足則添加元素到集合末尾,如果容量不滿足,則進行擴容</span>
     *<span style="color:#006600;">因爲這個方法擴容之後會將原來的數據進行拷貝,所以或消耗內存,所以在創建集合時,最後能夠指定一下集合的容量,這樣可以提交集合添加元素時的效率</span>
     * 
     */
    public void ensureCapacity(int minCapacity) {
	modCount++;
	int oldCapacity = elementData.length;
	if (minCapacity > oldCapacity) {
	    Object oldData[] = elementData;
	    int newCapacity = (oldCapacity * 3)/2 + 1;
    	    if (newCapacity < minCapacity)
		newCapacity = minCapacity;
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
	}
    }

    /**
     * 
     *<span style="color:#006600;">獲取集合中元素的個數</span>
     * 
     */
    public int size() {
	return size;
    }

    /**
     * 
     *<span style="color:#006600;">判斷集合中是否爲空,即沒有一個元素</span>
     * 
     */
    public boolean isEmpty() {
	return size == 0;
    }

    /**
     * 
     *<span style="background-color: rgb(0, 102, 0);"></span><span style="color:#006600;">判斷集合中是否含有某個元素</span>
     *
     * 
     */
    public boolean contains(Object o) {
	return indexOf(o) >= 0;
    }

    /**
     *
     * 
     * <span style="color:#009900;">獲取元素在在數組中距開始位置的位置</span>
     * 
     * 
     */
    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;
    }

    /**
     * 
     * 
     * <span style="color:#009900;">獲取元素在數組中從末尾開始的所在位置</span>
     *
     */
    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;
    }

    /**
     * 
     * <span style="color:#006600;">克隆方法</span>
     *
     * 
     */
    public Object clone() {
	try {
	    ArrayList<E> v = (ArrayList<E>) 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();
	}
    }

    /**
     *
     *
     *
     * <span style="color:#006600;">將集合轉爲數組</span>
     *
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /**
     * 
     * 
     * 
     * 
     * <span style="color:#006600;">將集合轉爲指定類型的數組</span>
     * 
     *
     */
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
	System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

    // Positional Access Operations

    /**
     * 
     *<span style="color:#006600;">獲取集合中指定位置的元素</span>
     */
    public E get(int index) {
	RangeCheck(index);

	return (E) elementData[index];
    }

    /**
     *
     * 
     *
     * 
     * <span style="color:#006600;">將集合中指定位置替換爲另一元素並返回替換前的元素</span>
     * 
     * 
     */
    public E set(int index, E element) {
	RangeCheck(index);

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

    /**
     * 
     *
     * <span style="color:#006600;">添加元素添加之前先進行擴容檢查</span>
     *
     */
    public boolean add(E e) {
	ensureCapacity(size + 1);  // Increments modCount!!
	elementData[size++] = e;
	return true;
    }

    /**
     *
     * <span style="color:#006600;">在指定位置添加元素</span>,<span style="color:#006600;">此方法可能會影響程序的性能,因爲添加的元素如果在數組的靠前位置,那麼數組的重組的開銷就會很大</span>
     * 
     *
     */
    public void add(int index, E element) {
	if (index > size || index < 0)
	    throw new IndexOutOfBoundsException(
		"Index: "+index+", Size: "+size);

	ensureCapacity(size+1);  // Increments modCount!!
	System.arraycopy(elementData, index, elementData, index + 1,
			 size - index);
	elementData[index] = element;
	size++;
    }

    /**
     * 
     * 
     * 
     *
     * <span style="color:#006600;">刪除指定位置的元素,同樣需要數組重組操作,如果刪除的元素特別靠前,那麼數組重組的消耗依然很大</span>
     * 
     * 
     */
    public E remove(int index) {
	RangeCheck(index);

  	modCount++;
	E oldValue = (E) elementData[index];

 	int numMoved = size - index - 1;
	 if (numMoved > 0)
	    System.arraycopy(elementData, index+1, elementData, index,
			     numMoved);
	elementData[--size] = null; // Let gc do its work

	return oldValue;
    }

    /**
     * 
     * <span style="color:#006600;">刪除指定元素</span>
     * 
     *
     */
    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;
    }

    /*
     *<span style="color:#006600;">刪除元素</span>
     * 
     */
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;//<span style="color:#006600;">要移動的元素個數</span>
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);//<span style="color:#006600;">數組重組</span>
        elementData[--size] = null; // <span style="color:#006600;">將重組之後的數組的最後位置的元素賦值爲null</span>
    }

    /**
     * 
     * <span style="color:#006600;">清空集合,實際就是變了數組,將數組的各個位置賦值爲Null</span>,<span style="color:#006600;">同時將size賦值爲0</span>
     */
    public void clear() {
	modCount++;

	// Let gc do its work
	for (int i = 0; i < size; i++)
	    elementData[i] = null;

	size = 0;
    }

    /**
     * 
     * 
     * 
     * 
     *<span style="color:#006600;"> 添加一個集合</span>
     * 
     * 
     *
     */
    public boolean addAll(Collection<? extends E> c) {
 	Object[] a = c.toArray();//<span style="color:#006600;">將集合轉爲數組</span>
        int numNew = a.length;//<span style="color:#006600;">取得數組的長度</span>
	ensureCapacity(size + numNew);  // <span style="color:#006600;">擴容</span>
        System.arraycopy(a, 0, elementData, size, numNew);//<span style="color:#006600;">將數組添加到elementData數組的末尾</span>
        size += numNew;
	return numNew != 0;
    }

    /**
     * 
     *
     * 
     * 
     *<span style="color:#006600;"> 添加一個集合到指定位置</span>
     * 
     *
     */
    public boolean addAll(int index, Collection<? extends E> c) {
	if (index > size || index < 0)
	    throw new IndexOutOfBoundsException(
		"Index: " + index + ", Size: " + size);

	Object[] a = c.toArray();
	int numNew = a.length;
	ensureCapacity(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;
    }

    /**
     *
     * 
     *
     * <span style="color:#006600;">刪除指定範圍的元素</span>
     * 
     *
     */
    protected void removeRange(int fromIndex, int toIndex) {
	modCount++;
	int numMoved = size - toIndex;//<span style="color:#006600;">要移動的元素個數</span>
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

	// Let gc do its work
	int newSize = size - (toIndex-fromIndex);
	while (size != newSize)
	    elementData[--size] = null;
    }

    /**
     * 
     * 
     * <span style="color:#FFFFFF;"><span style="background-color: rgb(0, 102, 0);">下標越界檢查</span></span>
     * 
     */
    private void RangeCheck(int index) {
	if (index >= size)
	    throw new IndexOutOfBoundsException(
		"Index: "+index+", Size: "+size);
    }

    /**
     * 
     * 
     *
     *<span style="color:#006600;"> 序列化對象</span>
     * 
     *
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
	// Write out element count, and any hidden stuff
	int expectedModCount = modCount;
	s.defaultWriteObject();

        // Write out array length
        s.writeInt(elementData.length);

	// Write out all elements in the proper order.
	for (int i=0; i<size; i++)
            s.writeObject(elementData[i]);

	if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }

    }

    /**
     * 
     * <span style="color:#006600;">反序列化</span>
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
	// Read in size, and any hidden stuff
	s.defaultReadObject();

        // Read in array length and allocate array
        int arrayLength = s.readInt();
        Object[] a = elementData = new Object[arrayLength];

	// Read in all elements in the proper order.
	for (int i=0; i<size; i++)
            a[i] = s.readObject();
    }
}

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