ArrayListソースコードの分析

26904 ワード

以下はArrayListソースコード実装、Java 1である.7版です.
ArrayListはスレッドが安全ではなく、秩序があり、重複要素を含むことができる.
次のように分析されます.
1.ArrayListクラスはAbstractListクラスを継承する、List、RandomAccess、Cloneable、javaを実現する.io.Serializableインタフェース.
2.ArrayListクラスで定義されている:DEFAULT_CAPACITY、EMPTY_ELEMENTDATA、elementData、size、MAX_ARRAY_SIZEなどの属性.
3.ArrayListクラスには、trimToSize、ensureCapacity、size、isEmpty、contains、indexof、lastIndexof、clone、toArray、get、set、elementData、add、remove、clear、addAll、rangeCheck、writeObject、readObject、listIterator、iteratorなどのメソッドが定義されています.
4.ArrayListクラスには、Itr、ListItr、SubListの3つの内部クラスが定義されています.ItrクラスはIteratorインタフェースを実現し、ListItrクラスはItrクラスを継承し、ListIteratorインタフェースを実現し、SubListクラスはAbstractListクラスを継承し、RandomAccessインタフェースを実現する.
4.1 Itrクラスにはcursor、lastRet、expectedModCount属性、hasNext、next、remove、checkForComodificationメソッドが定義されています.
4.2 ListItrクラスにはhasPrevious、nextIndex、previousIndex、previous、set、addメソッドが定義されています.
4.3 SubListクラスでは、parent、parentOffset、offset、size属性、set、get、size、add、remove、removeRange、addAll、iterator、listIterator、rangeCheck、checkForComodificationメソッドが定義されています.
5.ArrayListクラスでは、Arraysを使用する方法がある.copyOf()は、trimToSize、clone、コンストラクション関数などのレプリケーション操作を実現します.システムを使う方法もありますArraycopy()メソッドは、addAll、remove、add、removeRangeなどのレプリケーション操作を実現します.
6.ArrayListクラスでは、以下のようないくつかの共通のメソッドが定義されています.
6.1検査角度範囲方法
private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

6.2 iterator()メソッドがArrayListを巡回する場合、Itrクラスで定義されたcheckForComodificationメソッドは、ArrayListの操作中に他のスレッドがArrayListを操作しているかどうかをチェックする
final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

6.3 ArrayListにおけるいくつかの反復器の実現方法
public ListIterator listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }
 public ListIterator listIterator() {
        return new ListItr(0);
    }
    public Iterator iterator() {
        return new Itr();
    }

ArrayListにおける反復器は内部クラスをインスタンス化することによって実現されることが分かる.iteratorメソッドを直接呼び出すとItrクラスがインスタンス化されて戻り、listIterator()メソッドを直接呼び出すとListItrコンストラクション関数がインスタンス化されパラメータ0が入力され、listIterator(int index)メソッドを直接呼び出すとListItrコンストラクション関数がインスタンス化されパラメータindexが入力されます.
7.RandomAccessインタフェースのソースコードは以下の通りです.
public interface RandomAccess {
}

8.Cloneableインタフェースのソースコードは以下の通りです.
public interface Cloneable {
}

9.Serializableインタフェースのソースコードは以下の通りです.
public interface Serializable {
}

10.Listインタフェースのソースコードは以下の通りです.
public interface List extends Collection {
    int size();
    boolean isEmpty();
    boolean contains(Object o);
    Iterator iterator();
    Object[] toArray();
     T[] toArray(T[] a);
    boolean add(E e);
    boolean remove(Object o);
    boolean containsAll(Collection> c);
    boolean addAll(Collection extends E> c);
    boolean addAll(int index, Collection extends E> c);
    boolean removeAll(Collection> c);
    boolean retainAll(Collection> c);
    void clear();
    boolean equals(Object o);
    int hashCode();
    E get(int index);
    E set(int index, E element);
    void add(int index, E element);
    E remove(int index);
    int indexOf(Object o);
    int lastIndexOf(Object o);
    ListIterator listIterator();
    ListIterator listIterator(int index);
    List subList(int fromIndex, int toIndex);
}

11.Collectionインタフェースのソースコードは次のとおりです.
public interface Collection extends Iterable {
   
    int size();
    boolean isEmpty();
    boolean contains(Object o);
    Iterator iterator();
    Object[] toArray();
     T[] toArray(T[] a);
    boolean add(E e);
    boolean remove(Object o);
    boolean containsAll(Collection> c);
    boolean addAll(Collection extends E> c);
    boolean removeAll(Collection> c);
    boolean retainAll(Collection> c);
    void clear();
    boolean equals(Object o);
    int hashCode();
}

12.Iterableインタフェースのソースコードは次のとおりです.
public interface Iterable {

     Iterator iterator();
}

13.ArrayListクラスのソースコードは以下の通りである.
public class ArrayList extends AbstractList
        implements List, RandomAccess, Cloneable, java.io.Serializable
{   //     modCount  :The number of times this list has been structurally modified.

    private static final int DEFAULT_CAPACITY = 10;
    private static final Object[] EMPTY_ELEMENTDATA = {};
    private transient Object[] elementData;
    private int size;
    public ArrayList(int initialCapacity) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
    }
    public ArrayList() {
        super();
        this.elementData = EMPTY_ELEMENTDATA;
    }
    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);
    }
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = Arrays.copyOf(elementData, size);
        }
    }
    public void ensureCapacity(int minCapacity) {
        int minExpand = (elementData != EMPTY_ELEMENTDATA)?0:DEFAULT_CAPACITY;
        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == 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) {
        // 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);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
    public int size() {
        return size;
    }
    public boolean isEmpty() {
        return size == 0;
    }
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
    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;
    }
    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;
    }
    public Object clone() {
        try {
            @SuppressWarnings("unchecked")
                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();
        }
    }
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }
    @SuppressWarnings("unchecked")
    public  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;
    }

    @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);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }
    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; // clear to let GC do its work

        return oldValue;
    }
    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; // clear to let GC do its work
    }
    public void clear() {
        modCount++;

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

        size = 0;
    }
    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;
    }
    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)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);

        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex);
        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;
    }
    public boolean removeAll(Collection> c) {
        return batchRemove(c, false);
    }
    public boolean retainAll(Collection> 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)
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            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;
    }
    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 size as capacity for behavioural compatibility with clone()
        s.writeInt(size);

        // Write out all elements in the proper order.
        for (int i=0; i