1. 程式人生 > 程式設計 >ArrayList常用API原始碼分析

ArrayList常用API原始碼分析

3.1、ArrayList

簡介:

底層是可改變大小的陣列結構,實現了list介面,執行緒不安全,可以加入null元素,元素有序,允許重複。適合查詢,不適合指定位置的插入(adding n elements requires O(n) time)、刪除操作。

UML圖:

重要屬性
	/**
     * 預設初始容量.
     */
	private static final int DEFAULT_CAPACITY = 10;
	/**
     * 最大可以分配的陣列大小.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     */
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; 複製程式碼
3.1.1新增元素
/**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
public
boolean add(E e)
{ //擴容 ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } 複製程式碼
3.1.2刪除元素
/**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     *
     * @param
index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException {@inheritDoc} */
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; return oldValue; } 複製程式碼
3.1.3獲取指定位置的元素
/**
     * Returns the element at the specified position in this list.
     *
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        //索引位置檢查
        rangeCheck(index);

        return elementData(index);
    }
複製程式碼
3.1.4獲取某個元素第一次出現的索引位置
/**
     * Returns the index of the first occurrence of the specified element
     * in this list,or -1 if this list does not contain the element.
     * More formally,returns the lowest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,* or -1 if there is no such index.
     */
    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;
    }
複製程式碼
3.1.5獲取某個元素最後一次出現的索引位置
/**
     * Returns the index of the last occurrence of the specified element
     * in this list,returns the highest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,* or -1 if there is no such index.
     */
    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;
    }
複製程式碼
3.1.6更新某個索引位置的元素
/**
     * Replaces the element at the specified position in this list with
     * the specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index,E element) {
        //索引檢查
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
複製程式碼
3.1.7擴容
/**
     * 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;
        //新大小=原大小+原大小*0.5,即擴容到原來的1.5倍
        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);
    }
複製程式碼
3.1.8返回陣列大小
/**
     * Returns the number of elements in this list.
     *
     * @return the number of elements in this list
     */
    public int size() {
        return size;
    }
複製程式碼
3.1.9陣列是否為空判斷
/**
     * Returns <tt>true</tt> if this list contains no elements.
     *
     * @return <tt>true</tt> if this list contains no elements
     */
    public boolean isEmpty() {
        return size == 0;
    }
複製程式碼
3.1.10是否包含某個元素
/**
     * Returns <tt>true</tt> if this list contains the specified element.
     * More formally,returns <tt>true</tt> if and only if this list contains
     * at least one element <tt>e</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
     *
     * @param o element whose presence in this list is to be tested
     * @return <tt>true</tt> if this list contains the specified element
     */
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
複製程式碼
3.1.11清空陣列
/**
     * Removes all of the elements from this list.  The list will
     * be empty after this call returns.
     */
    public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }
複製程式碼
3.1.12交集操作
/**
     * Retains only the elements in this list that are contained in the
     * specified collection (optional operation).  In other words,removes
     * from this list all of its elements that are not contained in the
     * specified collection.
     *
     * @param c collection containing elements to be retained in this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws UnsupportedOperationException if the <tt>retainAll</tt> operation
     *         is not supported by this list
     * @throws ClassCastException if the class of an element of this list
     *         is incompatible with the specified collection
     * (<a href="Collection.html#optional-restrictions">optional</a>)
     * @throws NullPointerException if this list contains a null element and the
     *         specified collection does not permit null elements
     *         (<a href="Collection.html#optional-restrictions">optional</a>),*         or if the specified collection is null
     * @see #remove(Object)
     * @see #contains(Object)
     */
    boolean retainAll(Collection<?> c);
複製程式碼

3.1.13新增某個集合的所有元素

/**
     * Appends all of the elements in the specified collection to the end of
     * this list,in the order that they are returned by the specified
     * collection's iterator (optional operation).  The behavior of this
     * operation is undefined if the specified collection is modified while
     * the operation is in progress.  (Note that this will occur if the
     * specified collection is this list,and it's nonempty.)
     *
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws UnsupportedOperationException if the <tt>addAll</tt> operation
     *         is not supported by this list
     * @throws ClassCastException if the class of an element of the specified
     *         collection prevents it from being added to this list
     * @throws NullPointerException if the specified collection contains one
     *         or more null elements and this list does not permit null
     *         elements,or if the specified collection is null
     * @throws IllegalArgumentException if some property of an element of the
     *         specified collection prevents it from being added to this list
     * @see #add(Object)
     */
    boolean addAll(Collection<? extends E> c);
複製程式碼
3.1.13刪除陣列中所有在特定集合中出現的元素
 /**
     * Removes from this list all of its elements that are contained in the
     * specified collection (optional operation).
     *
     * @param c collection containing elements to be removed from this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws UnsupportedOperationException if the <tt>removeAll</tt> operation
     *         is not supported by this list
     * @throws ClassCastException if the class of an element of this list
     *         is incompatible with the specified collection
     * (<a href="Collection.html#optional-restrictions">optional</a>)
     * @throws NullPointerException if this list contains a null element and the
     *         specified collection does not permit null elements
     *         (<a href="Collection.html#optional-restrictions">optional</a>),*         or if the specified collection is null
     * @see #remove(Object)
     * @see #contains(Object)
     */
    boolean removeAll(Collection<?> c);
複製程式碼
示例:

public class ArrayListTest {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(null);
        list.add(1);
        list.add(2);
        System.out.println(list);
        System.out.println("list 第一次出現元素的索引值:" + list.indexOf(1));
        System.out.println("list 最後一次出現元素的索引值:" + list.lastIndexOf(1));
        list.set(1,6);
        System.out.println(list);
        System.out.println("list 是否為空?" + list.isEmpty());
        System.out.println("list 是否包含元素6?" + list.contains(6));
        list.clear();
        System.out.println("list 大小:" + list.size());

        //Arrays 中的 ArrayList 與 util 包下的 ArrayList 不同,要進行轉換
        List<Integer> temp2 = Arrays.asList(1,2,3);
        List<Integer> temp3 = Arrays.asList(2,3,4);
        List<Integer> list2 = new ArrayList<>(temp2);
        List<Integer> list3 = new ArrayList<>(temp3);
        list.addAll(list2);
        list.addAll(list3);
        System.out.println(list);
        list2.retainAll(list3);
        System.out.println("list2 與list3 的交集:" + list2);
        list.removeAll(list2);
        System.out.println("list3 與 list2 的差集:" + list);
        list.addAll(list2);
        System.out.println("list3 與 list2 的並集:" + list);


    }
}
複製程式碼
執行結果:
[1,null,1,2]
list 第一次出現元素的索引值:0
list 最後一次出現元素的索引值:2
[1,6,2]
list 是否為空?false
list 是否包含元素6true
list 大小:0
[1,4]
list2 與list3 的交集:[2,3]
list3 與 list2 的差集:[1,4]
list3 與 list2 的並集:[1,4,3]複製程式碼