ArrayList

发布时间 2023-10-30 15:46:23作者: anpeiyong

概述

  Resizable-array implementation of the <tt>List</tt> interface.  可变大小的数组(实现了List接口);

  Implements all optional list operations, and permits all elements, including null.  实现了List的所有操作,允许所有的元素(包括null)

  

  <p>The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>, <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant time.  

    size、isEmpty、get、set、iterator、listIterator操作需要 O(1)时间;

  The <tt>add</tt> operation runs in <i>amortized constant time</i>, that is, adding n elements requires O(n) time.  

    add操作 添加n个元素,需要O(n);

  

  <p>An application can increase the capacity of an<tt>ArrayList</tt> instance before adding a large number of elements using the <tt>ensureCapacity</tt> operation.  

    在添加大数量的元素前,会使用ensureCapacity确保ArrayList容量;

 

  Note that this implementation is not synchronized.  ArrayList的实现是非同步的;

  If multiple threads access an <tt>ArrayList</tt> instance concurrently, and at least one of the threads modifies the list structurally, it <i>must</i> be synchronized externally.

    如果多个线程并发访问ArrayList,必须在外部进行同步;

 

  A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.  

    结构修改:添加、删除元素、数组重置大小;  (多于多线程并发 需要进行同步操作)

  If no such object exists, the list should be "wrapped" using the {@link Collections#synchronizedList Collections.synchronizedList} method.  

    可以使用 Collections.synchronizedList 实现同步;

 

  The iterators returned by this class's {@link #iterator() iterator} and {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:

    iterator、listIterator 方法是fail-fast;    
  if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own {@link ListIterator#remove() remove}

  or {@linkListIterator#add(Object) add} methods, the iterator will throw a {@link ConcurrentModificationException}.

    如果创建了iterator,调用iterator的remove、add将会抛出ConcurrentModificationException(实际用的是子类的java.util.ArrayList.Itr)

链路

add

// java.util.ArrayList.add(E)
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    
    // java.util.ArrayList.ensureCapacityInternal
    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
    
    // java.util.ArrayList.calculateCapacity
    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
    
    // java.util.ArrayList.ensureExplicitCapacity
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;                                                     // modCount递增

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)                       // 容量不足,扩容
            grow(minCapacity);
    }
    
    // java.util.ArrayList.grow
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);             // 新容量 = 旧容量 + 旧容量/2
        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);          // 将元素旧数据 copy到 新数组中
    }

  

 

同步ArrayList(Collections.synchronizedList(new ArrayList<>());)

链路

add(E e)

// java.util.Collections.synchronizedList(java.util.List<T>)
    public static <T> List<T> synchronizedList(List<T> list) {
        return (list instanceof RandomAccess ?
                new SynchronizedRandomAccessList<>(list) :          // ArrayList实现了RandomAccess
                new SynchronizedList<>(list));
    }

    // java.util.Collections.SynchronizedRandomAccessList.SynchronizedRandomAccessList(java.util.List<E>)
    SynchronizedRandomAccessList(List<E> list) {
        super(list);
    }

    // java.util.Collections.SynchronizedList.SynchronizedList(java.util.List<E>)
    SynchronizedList(List<E> list) {
        super(list);
        this.list = list;
    }
    
    // java.util.Collections.SynchronizedCollection.add             // SynchronizedRandomAccessList继承了SynchronizedList,SynchronizedList继承了SynchronizedCollection,调用的是SynchronizedCollection的add
    public boolean add(E e) {
        synchronized (mutex) {return c.add(e);}
    }