ArrayListの共通APIのソースコード解析

3.1、ArrayListに

要約:

アレイの構造を変化させることができる基礎となることは、スレッドセーフな、実装されたインタフェースのリストのサイズであり、ヌル要素に追加することができ、反復を可能にする要素を命じました。指定された挿入位置に適した、適していない発見(追加n個の要素はO(N)時間を要する)、削除操作。

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, or -1 if this list does not contain the element.
     * More formally, 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, 1, 2]
list 是否为空?false
list 是否包含元素6true
list 大小:0
[1, 2, 3, 2, 3, 4]
list2 与list3 的交集:[2, 3]
list3 与 list2 的差集:[1, 4]
list3 与 list2 的并集:[1, 4, 2, 3]复制代码

おすすめ

転載: juejin.im/post/5dd746d76fb9a07acd55c102