• Java集合(三)—ArrayList集合(JDK1.8)


    Java集合(三)—ArrayList集合(JDK1.8)

    1. 参考博客

    http://blog.csdn.net/ITermeng/article/details/72725878
    http://www.cnblogs.com/skywang12345/p/3308556.html
    http://blog.csdn.net/chun0801/article/details/51481877

    2. 特点

    • List接口的可变数组的实现。实现了所有可选列表操作,并允许包括null在内的所有元素。
    • 非线程安全。在多线程情况下操作时,一定要加上synchronized,才能保证多个线程同时对ArrayList进行访问时数据的安全性。
    • 底层使用的数据结构是数组。
    • 适合查改,弱于增删。
    • 实现了Serializable接口,因此它支持序列化,能够通过序列化传输。
    • 实现了RandomAccess接口,支持快速随机访问,实际上就是通过下标序号进行快速访问。
    • 实现了Cloneable接口,能被克隆。

    3. 源码

    package java.util;
    
    import java.util.function.Consumer;
    import java.util.function.Predicate;
    import java.util.function.UnaryOperator;
    
    
    public class ArrayList<E> extends AbstractList<E>
            implements List<E>, RandomAccess, Cloneable, java.io.Serializable
    {
    	//序列号版本
        private static final long serialVersionUID = 8683452581122892189L;
    
        //默认的数组容量大小为10
        private static final int DEFAULT_CAPACITY = 10;
    
        
        //用于空实例的共享空数组实例。
        private static final Object[] EMPTY_ELEMENTDATA = {};
    
       
    	//用于默认大小的空实例的共享空数组实例,与EMPTY_ELEMENTDATA不同的是,当添加第一个元素时知道扩容多少。
        private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    
       
    	//ArrayList用它来储存,该数组的大小就是ArrayList的大小,任何空数组(elementData)== 
    	//(DEFAULTCAPACITY_EMPTY_ELEMENTDATA)在第一个元素添加时,一默认容量10增加。
        transient Object[] elementData; // 不置为私有域是为了方便嵌套类访问
    
       
        private int size;//实际元素个数
    
       //带参的初始化构造函数 参数表示集合的大小
        public ArrayList(int initialCapacity) {
            if (initialCapacity > 0) {
                this.elementData = new Object[initialCapacity];
            } else if (initialCapacity == 0) {
                this.elementData = EMPTY_ELEMENTDATA;//新建一个数组
            } else {
                throw new IllegalArgumentException("Illegal Capacity: "+
                                                   initialCapacity);
            }
        }
    
        //无参构造器,默认初始化集合大小为10
        public ArrayList() {
            this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
        }
    
        //创建参数为一个collection集合的的arrylist的构造器
        public ArrayList(Collection<? extends E> c) {
            elementData = c.toArray();
            if ((size = elementData.length) != 0) {
                // c.toArray might (incorrectly) not return Object[] (see 6260652)
                if (elementData.getClass() != Object[].class)
                    elementData = Arrays.copyOf(elementData, size, Object[].class);
            } else {
                // replace with empty array.
                this.elementData = EMPTY_ELEMENTDATA;
            }
        }
    
        //将当前容量值设为实际元素个数(去掉数组中空元素部分让数组元素与数组长度相等)
        public void trimToSize() {
            modCount++;
            if (size < elementData.length) {
                elementData = (size == 0)
                  ? EMPTY_ELEMENTDATA
                  : Arrays.copyOf(elementData, size);
            }
        }
    
    	//增加ArrayList的容量,如果必要,要保证它能容纳最小数量的元素,最小数量由参数(minCapacity)指定。
        public void ensureCapacity(int minCapacity) {
            int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
                // any size if not default element table
                ? 0
                // larger than default for default empty table. It's already
                // supposed to be at default size.
                : DEFAULT_CAPACITY;
    
            if (minCapacity > minExpand) {
                ensureExplicitCapacity(minCapacity);
            }
        }
    	
    	//
        private void ensureCapacityInternal(int minCapacity) {
            if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
                minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
            }
    
            ensureExplicitCapacity(minCapacity);
        }
    
        private void ensureExplicitCapacity(int minCapacity) {
            modCount++;
            // overflow-conscious code
            if (minCapacity - elementData.length > 0)//若传入的最小容量大小大于数组目前的大小,调用grow方法增容。
                grow(minCapacity);
        }
    
    	 
    	//允许分配的最大的数组长度,尝试分配较大的数组可能会导致OutOfMemoryError:请求的数组大小超过VM限制
        private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    
       
    	//增加容量已确保能容纳指定的最小元素个数(minCapacity)
        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;
        }
    
        //返回集合(ArrayList)中的元素个数
        public int size() {
            return size;
        }
    
        //判断ArrayList是否为空
        public boolean isEmpty() {
            return size == 0;
        }
    
        //返回是否包含指定元素(Object o)
        public boolean contains(Object o) {
            return indexOf(o) >= 0;
        }
    
       
    	//返回list中第一次出现的指定元素(O)的位置,不存在该元素返回-1.正向搜索。
        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;
        }
    
        
    	//返回在这个ArrayList实例的一个浅拷贝(元素本身并没有被复制)
        public Object clone() {
            try {
                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(e);
            }
        }
    
    
    	//返回一个包含集合中所有元素的数组,元素顺序为从第一个到最后一个(这个方法会分配一个新的数组)
        public Object[] toArray() {
            return Arrays.copyOf(elementData, size);
        }
    
        /**
         * Returns an array containing all of the elements in this list in proper
         * sequence (from first to last element); the runtime type of the returned
         * array is that of the specified array.  If the list fits in the
         * specified array, it is returned therein.  Otherwise, a new array is
         * allocated with the runtime type of the specified array and the size of
         * this list.
         *
         * <p>If the list fits in the specified array with room to spare
         * (i.e., the array has more elements than the list), the element in
         * the array immediately following the end of the collection is set to
         * <tt>null</tt>.  (This is useful in determining the length of the
         * list <i>only</i> if the caller knows that the list does not contain
         * any null elements.)
         *
         * @param a the array into which the elements of the list are to
         *          be stored, if it is big enough; otherwise, a new array of the
         *          same runtime type is allocated for this purpose.
         * @return an array containing the elements of the list
         * @throws ArrayStoreException if the runtime type of the specified array
         *         is not a supertype of the runtime type of every element in
         *         this list
         * @throws NullPointerException if the specified array is null
         */
        @SuppressWarnings("unchecked")
        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;
        }
    
    
       //返回索引位置的元素,没有检查的方法
        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
        }
    
    	//清空集合,将元素全部置为null
        public void clear() {
            modCount++;
    
            // clear to let GC do its work
            for (int i = 0; i < size; i++)
                elementData[i] = null;
    
            size = 0;
        }
    
       // 将集合c追加到ArrayList中   
        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;
        }
    
        // 从index位置开始,将集合c添加到ArrayList
        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;
        }
    
       // 删除fromIndex到toIndex之间的全部元素。 
        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));
        }
    
          
        //此方法被用于 add 和 addAll,检查下标是否越界.
        private void rangeCheckForAdd(int index) {
            if (index > size || index < 0)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }
    
        /**
         * Constructs an IndexOutOfBoundsException detail message.
         * Of the many possible refactorings of the error handling code,
         * this "outlining" performs best with both server and client VMs.
         */
        private String outOfBoundsMsg(int index) {
            return "Index: "+index+", Size: "+size;
        }
    
        //从此列表中删除其中包含的所有元素
        public boolean removeAll(Collection<?> c) {
            Objects.requireNonNull(c);
            return batchRemove(c, false);
        }
    
        //仅保留此列表中指定集合包含的元素,换句话说,从这个列表中删除所有不包含在指定的集合中的元素。
        public boolean retainAll(Collection<?> c) {
            Objects.requireNonNull(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;
        }
    
         /* 
        * java.io.Serializable的写入函数    
        * 将ArrayList的“容量,所有的元素值”都写入到输出流中    
        */
        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<size; i++) {
                s.writeObject(elementData[i]);
            }
    
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
        }
    
        // java.io.Serializable的读取函数:根据写入方式读出    
        // 先将ArrayList的“容量”读出,然后将“所有的元素值”读出    
        private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
            elementData = EMPTY_ELEMENTDATA;
    
            // Read in size, and any hidden stuff
            s.defaultReadObject();
    
            // Read in capacity
            s.readInt(); // ignored
    
            if (size > 0) {
                // be like clone(), allocate array based upon size not capacity
                ensureCapacityInternal(size);
    
                Object[] a = elementData;
                // Read in all elements in the proper order.
                for (int i=0; i<size; i++) {
                    a[i] = s.readObject();
                }
            }
        }
    
        //返回列表中的列表迭代器
        public ListIterator<E> listIterator(int index) {
            if (index < 0 || index > size)
                throw new IndexOutOfBoundsException("Index: "+index);
            return new ListItr(index);
        }
    
        /**
         * Returns a list iterator over the elements in this list (in proper
         * sequence).
         *
         * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
         *
         * @see #listIterator(int)
         */
        public ListIterator<E> listIterator() {
            return new ListItr(0);
        }
    
        /**
         * Returns an iterator over the elements in this list in proper sequence.
         *
         * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
         *
         * @return an iterator over the elements in this list in proper sequence
         */
        public Iterator<E> iterator() {
            return new Itr();
        }
    
        /**
         * An optimized version of AbstractList.Itr
         */
        private class Itr implements Iterator<E> {
            int cursor;       // index of next element to return
            int lastRet = -1; // index of last element returned; -1 if no such
            int expectedModCount = modCount;
    
            public boolean hasNext() {
                return cursor != size;
            }
    
            @SuppressWarnings("unchecked")
            public E next() {
                checkForComodification();
                int i = cursor;
                if (i >= size)
                    throw new NoSuchElementException();
                Object[] elementData = ArrayList.this.elementData;
                if (i >= elementData.length)
                    throw new ConcurrentModificationException();
                cursor = i + 1;
                return (E) elementData[lastRet = i];
            }
    
            public void remove() {
                if (lastRet < 0)
                    throw new IllegalStateException();
                checkForComodification();
    
                try {
                    ArrayList.this.remove(lastRet);
                    cursor = lastRet;
                    lastRet = -1;
                    expectedModCount = modCount;
                } catch (IndexOutOfBoundsException ex) {
                    throw new ConcurrentModificationException();
                }
            }
    
            @Override
            @SuppressWarnings("unchecked")
            public void forEachRemaining(Consumer<? super E> consumer) {
                Objects.requireNonNull(consumer);
                final int size = ArrayList.this.size;
                int i = cursor;
                if (i >= size) {
                    return;
                }
                final Object[] elementData = ArrayList.this.elementData;
                if (i >= elementData.length) {
                    throw new ConcurrentModificationException();
                }
                while (i != size && modCount == expectedModCount) {
                    consumer.accept((E) elementData[i++]);
                }
                // update once at end of iteration to reduce heap write traffic
                cursor = i;
                lastRet = i - 1;
                checkForComodification();
            }
    
            final void checkForComodification() {
                if (modCount != expectedModCount)
                    throw new ConcurrentModificationException();
            }
        }
    
        /**
         * An optimized version of AbstractList.ListItr
         */
        private class ListItr extends Itr implements ListIterator<E> {
            ListItr(int index) {
                super();
                cursor = index;
            }
    
            public boolean hasPrevious() {
                return cursor != 0;
            }
    
            public int nextIndex() {
                return cursor;
            }
    
            public int previousIndex() {
                return cursor - 1;
            }
    
            @SuppressWarnings("unchecked")
            public E previous() {
                checkForComodification();
                int i = cursor - 1;
                if (i < 0)
                    throw new NoSuchElementException();
                Object[] elementData = ArrayList.this.elementData;
                if (i >= elementData.length)
                    throw new ConcurrentModificationException();
                cursor = i;
                return (E) elementData[lastRet = i];
            }
    
            public void set(E e) {
                if (lastRet < 0)
                    throw new IllegalStateException();
                checkForComodification();
    
                try {
                    ArrayList.this.set(lastRet, e);
                } catch (IndexOutOfBoundsException ex) {
                    throw new ConcurrentModificationException();
                }
            }
    
            public void add(E e) {
                checkForComodification();
    
                try {
                    int i = cursor;
                    ArrayList.this.add(i, e);
                    cursor = i + 1;
                    lastRet = -1;
                    expectedModCount = modCount;
                } catch (IndexOutOfBoundsException ex) {
                    throw new ConcurrentModificationException();
                }
            }
        }
    
        /**
         * Returns a view of the portion of this list between the specified
         * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.  (If
         * {@code fromIndex} and {@code toIndex} are equal, the returned list is
         * empty.)  The returned list is backed by this list, so non-structural
         * changes in the returned list are reflected in this list, and vice-versa.
         * The returned list supports all of the optional list operations.
         *
         * <p>This method eliminates the need for explicit range operations (of
         * the sort that commonly exist for arrays).  Any operation that expects
         * a list can be used as a range operation by passing a subList view
         * instead of a whole list.  For example, the following idiom
         * removes a range of elements from a list:
         * <pre>
         *      list.subList(from, to).clear();
         * </pre>
         * Similar idioms may be constructed for {@link #indexOf(Object)} and
         * {@link #lastIndexOf(Object)}, and all of the algorithms in the
         * {@link Collections} class can be applied to a subList.
         *
         * <p>The semantics of the list returned by this method become undefined if
         * the backing list (i.e., this list) is <i>structurally modified</i> in
         * any way other than via the returned list.  (Structural modifications are
         * those that change the size of this list, or otherwise perturb it in such
         * a fashion that iterations in progress may yield incorrect results.)
         *
         * @throws IndexOutOfBoundsException {@inheritDoc}
         * @throws IllegalArgumentException {@inheritDoc}
         */
        public List<E> subList(int fromIndex, int toIndex) {
            subListRangeCheck(fromIndex, toIndex, size);
            return new SubList(this, 0, fromIndex, toIndex);
        }
    
        static void subListRangeCheck(int fromIndex, int toIndex, int size) {
            if (fromIndex < 0)
                throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
            if (toIndex > size)
                throw new IndexOutOfBoundsException("toIndex = " + toIndex);
            if (fromIndex > toIndex)
                throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                                   ") > toIndex(" + toIndex + ")");
        }
    
        private class SubList extends AbstractList<E> implements RandomAccess {
            private final AbstractList<E> parent;
            private final int parentOffset;
            private final int offset;
            int size;
    
            SubList(AbstractList<E> parent,
                    int offset, int fromIndex, int toIndex) {
                this.parent = parent;
                this.parentOffset = fromIndex;
                this.offset = offset + fromIndex;
                this.size = toIndex - fromIndex;
                this.modCount = ArrayList.this.modCount;
            }
    
            public E set(int index, E e) {
                rangeCheck(index);
                checkForComodification();
                E oldValue = ArrayList.this.elementData(offset + index);
                ArrayList.this.elementData[offset + index] = e;
                return oldValue;
            }
    
            public E get(int index) {
                rangeCheck(index);
                checkForComodification();
                return ArrayList.this.elementData(offset + index);
            }
    
            public int size() {
                checkForComodification();
                return this.size;
            }
    
            public void add(int index, E e) {
                rangeCheckForAdd(index);
                checkForComodification();
                parent.add(parentOffset + index, e);
                this.modCount = parent.modCount;
                this.size++;
            }
    
            public E remove(int index) {
                rangeCheck(index);
                checkForComodification();
                E result = parent.remove(parentOffset + index);
                this.modCount = parent.modCount;
                this.size--;
                return result;
            }
    
            protected void removeRange(int fromIndex, int toIndex) {
                checkForComodification();
                parent.removeRange(parentOffset + fromIndex,
                                   parentOffset + toIndex);
                this.modCount = parent.modCount;
                this.size -= toIndex - fromIndex;
            }
    
            public boolean addAll(Collection<? extends E> c) {
                return addAll(this.size, c);
            }
    
            public boolean addAll(int index, Collection<? extends E> c) {
                rangeCheckForAdd(index);
                int cSize = c.size();
                if (cSize==0)
                    return false;
    
                checkForComodification();
                parent.addAll(parentOffset + index, c);
                this.modCount = parent.modCount;
                this.size += cSize;
                return true;
            }
    
            public Iterator<E> iterator() {
                return listIterator();
            }
    
            public ListIterator<E> listIterator(final int index) {
                checkForComodification();
                rangeCheckForAdd(index);
                final int offset = this.offset;
    
                return new ListIterator<E>() {
                    int cursor = index;
                    int lastRet = -1;
                    int expectedModCount = ArrayList.this.modCount;
    
                    public boolean hasNext() {
                        return cursor != SubList.this.size;
                    }
    
                    @SuppressWarnings("unchecked")
                    public E next() {
                        checkForComodification();
                        int i = cursor;
                        if (i >= SubList.this.size)
                            throw new NoSuchElementException();
                        Object[] elementData = ArrayList.this.elementData;
                        if (offset + i >= elementData.length)
                            throw new ConcurrentModificationException();
                        cursor = i + 1;
                        return (E) elementData[offset + (lastRet = i)];
                    }
    
                    public boolean hasPrevious() {
                        return cursor != 0;
                    }
    
                    @SuppressWarnings("unchecked")
                    public E previous() {
                        checkForComodification();
                        int i = cursor - 1;
                        if (i < 0)
                            throw new NoSuchElementException();
                        Object[] elementData = ArrayList.this.elementData;
                        if (offset + i >= elementData.length)
                            throw new ConcurrentModificationException();
                        cursor = i;
                        return (E) elementData[offset + (lastRet = i)];
                    }
    
                    @SuppressWarnings("unchecked")
                    public void forEachRemaining(Consumer<? super E> consumer) {
                        Objects.requireNonNull(consumer);
                        final int size = SubList.this.size;
                        int i = cursor;
                        if (i >= size) {
                            return;
                        }
                        final Object[] elementData = ArrayList.this.elementData;
                        if (offset + i >= elementData.length) {
                            throw new ConcurrentModificationException();
                        }
                        while (i != size && modCount == expectedModCount) {
                            consumer.accept((E) elementData[offset + (i++)]);
                        }
                        // update once at end of iteration to reduce heap write traffic
                        lastRet = cursor = i;
                        checkForComodification();
                    }
    
                    public int nextIndex() {
                        return cursor;
                    }
    
                    public int previousIndex() {
                        return cursor - 1;
                    }
    
                    public void remove() {
                        if (lastRet < 0)
                            throw new IllegalStateException();
                        checkForComodification();
    
                        try {
                            SubList.this.remove(lastRet);
                            cursor = lastRet;
                            lastRet = -1;
                            expectedModCount = ArrayList.this.modCount;
                        } catch (IndexOutOfBoundsException ex) {
                            throw new ConcurrentModificationException();
                        }
                    }
    
                    public void set(E e) {
                        if (lastRet < 0)
                            throw new IllegalStateException();
                        checkForComodification();
    
                        try {
                            ArrayList.this.set(offset + lastRet, e);
                        } catch (IndexOutOfBoundsException ex) {
                            throw new ConcurrentModificationException();
                        }
                    }
    
                    public void add(E e) {
                        checkForComodification();
    
                        try {
                            int i = cursor;
                            SubList.this.add(i, e);
                            cursor = i + 1;
                            lastRet = -1;
                            expectedModCount = ArrayList.this.modCount;
                        } catch (IndexOutOfBoundsException ex) {
                            throw new ConcurrentModificationException();
                        }
                    }
    
                    final void checkForComodification() {
                        if (expectedModCount != ArrayList.this.modCount)
                            throw new ConcurrentModificationException();
                    }
                };
            }
    
            public List<E> subList(int fromIndex, int toIndex) {
                subListRangeCheck(fromIndex, toIndex, size);
                return new SubList(this, offset, fromIndex, toIndex);
            }
    
            private void rangeCheck(int index) {
                if (index < 0 || index >= this.size)
                    throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
            }
    
            private void rangeCheckForAdd(int index) {
                if (index < 0 || index > this.size)
                    throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
            }
    
            private String outOfBoundsMsg(int index) {
                return "Index: "+index+", Size: "+this.size;
            }
    
            private void checkForComodification() {
                if (ArrayList.this.modCount != this.modCount)
                    throw new ConcurrentModificationException();
            }
    
            public Spliterator<E> spliterator() {
                checkForComodification();
                return new ArrayListSpliterator<E>(ArrayList.this, offset,
                                                   offset + this.size, this.modCount);
            }
        }
    
        @Override
        public void forEach(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            final int expectedModCount = modCount;
            @SuppressWarnings("unchecked")
            final E[] elementData = (E[]) this.elementData;
            final int size = this.size;
            for (int i=0; modCount == expectedModCount && i < size; i++) {
                action.accept(elementData[i]);
            }
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
        }
    
        /**
         * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
         * and <em>fail-fast</em> {@link Spliterator} over the elements in this
         * list.
         *
         * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
         * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
         * Overriding implementations should document the reporting of additional
         * characteristic values.
         *
         * @return a {@code Spliterator} over the elements in this list
         * @since 1.8
         */
        @Override
        public Spliterator<E> spliterator() {
            return new ArrayListSpliterator<>(this, 0, -1, 0);
        }
    
        /** Index-based split-by-two, lazily initialized Spliterator */
        static final class ArrayListSpliterator<E> implements Spliterator<E> {
    
            /*
             * If ArrayLists were immutable, or structurally immutable (no
             * adds, removes, etc), we could implement their spliterators
             * with Arrays.spliterator. Instead we detect as much
             * interference during traversal as practical without
             * sacrificing much performance. We rely primarily on
             * modCounts. These are not guaranteed to detect concurrency
             * violations, and are sometimes overly conservative about
             * within-thread interference, but detect enough problems to
             * be worthwhile in practice. To carry this out, we (1) lazily
             * initialize fence and expectedModCount until the latest
             * point that we need to commit to the state we are checking
             * against; thus improving precision.  (This doesn't apply to
             * SubLists, that create spliterators with current non-lazy
             * values).  (2) We perform only a single
             * ConcurrentModificationException check at the end of forEach
             * (the most performance-sensitive method). When using forEach
             * (as opposed to iterators), we can normally only detect
             * interference after actions, not before. Further
             * CME-triggering checks apply to all other possible
             * violations of assumptions for example null or too-small
             * elementData array given its size(), that could only have
             * occurred due to interference.  This allows the inner loop
             * of forEach to run without any further checks, and
             * simplifies lambda-resolution. While this does entail a
             * number of checks, note that in the common case of
             * list.stream().forEach(a), no checks or other computation
             * occur anywhere other than inside forEach itself.  The other
             * less-often-used methods cannot take advantage of most of
             * these streamlinings.
             */
    
            private final ArrayList<E> list;
            private int index; // current index, modified on advance/split
            private int fence; // -1 until used; then one past last index
            private int expectedModCount; // initialized when fence set
    
            /** Create new spliterator covering the given  range */
            ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
                                 int expectedModCount) {
                this.list = list; // OK if null unless traversed
                this.index = origin;
                this.fence = fence;
                this.expectedModCount = expectedModCount;
            }
    
            private int getFence() { // initialize fence to size on first use
                int hi; // (a specialized variant appears in method forEach)
                ArrayList<E> lst;
                if ((hi = fence) < 0) {
                    if ((lst = list) == null)
                        hi = fence = 0;
                    else {
                        expectedModCount = lst.modCount;
                        hi = fence = lst.size;
                    }
                }
                return hi;
            }
    
            public ArrayListSpliterator<E> trySplit() {
                int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
                return (lo >= mid) ? null : // divide range in half unless too small
                    new ArrayListSpliterator<E>(list, lo, index = mid,
                                                expectedModCount);
            }
    
            public boolean tryAdvance(Consumer<? super E> action) {
                if (action == null)
                    throw new NullPointerException();
                int hi = getFence(), i = index;
                if (i < hi) {
                    index = i + 1;
                    @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
                    action.accept(e);
                    if (list.modCount != expectedModCount)
                        throw new ConcurrentModificationException();
                    return true;
                }
                return false;
            }
    
            public void forEachRemaining(Consumer<? super E> action) {
                int i, hi, mc; // hoist accesses and checks from loop
                ArrayList<E> lst; Object[] a;
                if (action == null)
                    throw new NullPointerException();
                if ((lst = list) != null && (a = lst.elementData) != null) {
                    if ((hi = fence) < 0) {
                        mc = lst.modCount;
                        hi = lst.size;
                    }
                    else
                        mc = expectedModCount;
                    if ((i = index) >= 0 && (index = hi) <= a.length) {
                        for (; i < hi; ++i) {
                            @SuppressWarnings("unchecked") E e = (E) a[i];
                            action.accept(e);
                        }
                        if (lst.modCount == mc)
                            return;
                    }
                }
                throw new ConcurrentModificationException();
            }
    
            public long estimateSize() {
                return (long) (getFence() - index);
            }
    
            public int characteristics() {
                return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
            }
        }
    
        @Override
        public boolean removeIf(Predicate<? super E> filter) {
            Objects.requireNonNull(filter);
            // figure out which elements are to be removed
            // any exception thrown from the filter predicate at this stage
            // will leave the collection unmodified
            int removeCount = 0;
            final BitSet removeSet = new BitSet(size);
            final int expectedModCount = modCount;
            final int size = this.size;
            for (int i=0; modCount == expectedModCount && i < size; i++) {
                @SuppressWarnings("unchecked")
                final E element = (E) elementData[i];
                if (filter.test(element)) {
                    removeSet.set(i);
                    removeCount++;
                }
            }
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
    
            // shift surviving elements left over the spaces left by removed elements
            final boolean anyToRemove = removeCount > 0;
            if (anyToRemove) {
                final int newSize = size - removeCount;
                for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
                    i = removeSet.nextClearBit(i);
                    elementData[j] = elementData[i];
                }
                for (int k=newSize; k < size; k++) {
                    elementData[k] = null;  // Let gc do its work
                }
                this.size = newSize;
                if (modCount != expectedModCount) {
                    throw new ConcurrentModificationException();
                }
                modCount++;
            }
    
            return anyToRemove;
        }
    
        @Override
        @SuppressWarnings("unchecked")
        public void replaceAll(UnaryOperator<E> operator) {
            Objects.requireNonNull(operator);
            final int expectedModCount = modCount;
            final int size = this.size;
            for (int i=0; modCount == expectedModCount && i < size; i++) {
                elementData[i] = operator.apply((E) elementData[i]);
            }
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }
    
        @Override
        @SuppressWarnings("unchecked")
        public void sort(Comparator<? super E> c) {
            final int expectedModCount = modCount;
            Arrays.sort((E[]) elementData, 0, size, c);
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }
    }
    

    4. 源码重点分析

    1.1 构造函数

    ArrayList类有三个重载的构造方法:

    1. ArrayList() 无参数默认构造方法,创建列表(即数组)的容量大小默认为10。
    2. ArrayList(int initialCapacity) 带有int参数的构造方法,参数为创建列表时要求容量,创建一个大小为initialCapacity的列表。
    3. ArrayList( Collection< ? extends E > c) 带有Collection参数的构造方法,将Collection转化为数组赋给ArrayList的实现数组elementData。

    1.2 ensureCapacity方法

    ensureCapacity用于检查是否需要扩容

        public void ensureCapacity(int minCapacity) {
            int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
                // any size if not default element table
                ? 0
                // larger than default for default empty table. It's already
                // supposed to be at default size.
                : DEFAULT_CAPACITY;
    
            if (minCapacity > minExpand) {
                ensureExplicitCapacity(minCapacity);
            }
        }
    

    小结:如果创建ArrayList时用的是无参构造器,则第一次插入时会进行一次扩容并且扩到默认数组大小10
    如果是使用带有容量参数的构造器且minCapacity=0时,则不会进行这一步,直接扩展数组容量为minCapacity
    这就导致一个结果,扩容之后带参数的构造器的数组length为1,而默认的为10所以,带容量参数的初始化时注意自己需要的大小

        private void ensureCapacityInternal(int minCapacity) {
            if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
                minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
            }
    
            ensureExplicitCapacity(minCapacity);
        }
    
        private void ensureExplicitCapacity(int minCapacity) {
            modCount++;
            // overflow-conscious code
            if (minCapacity - elementData.length > 0)
                grow(minCapacity);
        }
    	
        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;
        }
    

    1.3 modCount的作用

    每一次对数组做添加元素,删除元素等改变数组大小或者容量的操作时都会引起对modCount的加1, 究竟这个值有什么作用呢?

    //返回一个遍历的指针
    public Iterator<E> iterator() {
        return new Itr();
    }
    private class Itr implements Iterator<E> {
        int cursor; // 下一个要返回的元素的下标
        int lastRet = -1; // 最后一个元素的下标
        int expectedModCount = modCount;  //这个的作用就是当用itr来遍历集合时,不允许往里面添加或者删除元素
    
        public boolean hasNext() {//hasNext方法不会检查expectedModCount 的值,不会引发ConcurrentModificationException异常
            return cursor != size;
        }
    
        @SuppressWarnings("unchecked")
        public E next() {//next方法在最开始的时候就会使用checkForComodification进行检查
        //所以如果在调用next之前对集合进行了改变则会抛出异常
            checkForComodification();//检查是否改变
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = MyArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
        //remove方法首先会调用checkForComodification进行检查
        //同时,在MyArrayList.this.remove(lastRet)时会改变modCount,expectedModCount = modCount
        //又让情况变为正常,所以删除之后这两个的值又会想等,在之后调用next的方法时不会炮竹异常
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();
    
            try {
                MyArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = MyArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = MyArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }
    
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
    

    例如:使用iterator

        Iterator<Integer> it = array.iterator();
            while(it.hasNext()){
                //array.add(4);  会导致modCount发生变化,从而导致next方法的checkModCount抛出异常
                int value = it.next();
                //array.remove(new Integer(value));同样会导致modCount发生变化
                it.remove();//但是可以这样,因为Iterator的remove方法删除元素之后对modCount又进行了复原
                System.out.println(value);
            }
    

    1.4 Arrays.copyof() 方法和 System.arraycopy() 方法

    ArrayList的实现中大量地调用了此功能,即将元素拷贝到新的数组。来查看其代码实现,这里有多个重载方法,实现思路相同。

    public static <T> T[] copyOf(T[] original, int newLength) {  
        return (T[]) copyOf(original, newLength, original.getClass());  
    }
    
    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {  
        T[] copy = ((Object)newType == (Object)Object[].class)  
            ? (T[]) new Object[newLength]  
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);  
        System.arraycopy(original, 0, copy, 0,  
                         Math.min(original.length, newLength));  
        return copy;  
    }  
    

    所以其实真正调用的是copyOf()方法,可以看出该方法实际上是在其内部又创建了一个长度为newlength的数组,调用System.arraycopy()方法,将原来数组中的元素复制到了新的数组中。

    而System.arraycopy()方法被标记为native,调用了系统的C/C++代码,只能在openJDK中查看源码。这里简单说明一下,此方法实际上调用了C语言的memmove()函数,所以它可以保证同一个数组内元素的正确复制和移动,效率比一般的复制方法高,适合用于批量处理数组。在Java中也比较推荐使用此方法达到更好的效率。

    1.5 toArray方法

     (1) public Object[] toArray()

     public Object[] toArray() {
           return Arrays.copyOf(elementData, size);
       }
    

    此方法直接调用Arrays.copyof() 并将结果返回,这样做有潜在危机,有可能会抛出ClassCastException异常。例如:直接用向下转型的方法,将整个ArrayList集合转变为指定类型的Array数组,便会抛出该异常。但是,如果转化为Array数组时不向下转型,而是将每个元素向下转型,则不会抛出该异常。这样的做法明显效率低下,且不太方便。

     (2) public T[] toArray(T[] a) ()

        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;
        }
    

    方法一开始会进行判断,若数组a的容量个数小于ArrayList的元素个数,则新建一个T[]数组,数组大小是“ArrayList的元素个数”,并将“ArrayList”全部拷贝到新数组中 。反之则将ArrayList的全部元素都拷贝到数组a中。该方法可以直接将ArrayList转换得到的Array进行整体向下转型,效率较高。

    1.6 add()方法

    • add()
      功能就是将新元素增加到列表尾部。照例,首先调用ensureCapacity方法来确保容量是否满足,即确保列表中还有额外的一个容量,然后将列表的末尾值设置为新值,返回True代表成功。

    • add(int index, E element)
      不同于上一个函数将新元素直接增加到列表尾部,此功能是将新元素增加到指定位置index。来查看方法实现,由于都是增加元素必然会调用到ensureCapacity方法来确保容量是否满足,可是在此操作之前还需判断index是否合法(指定下标小于0或大于列表总长度)。一切准备就绪开始插入元素,注意ArrayList底层原理是数组,所以需要将列表中index后的元素全部往后移动一位,空出一个位置留给新元素,这里就用到上面介绍到的System.arraycopy()方法进行元素拷贝。最后赋值、总长度加1即完成操作。

    1.7 remove()删除方法

    • remove(int index)
      功能即移除此列表中指定位置上的元素。来查看方法实现,照例,首先判断下标是否合法,然后同增加方法一样,需要将列表中index后的值全部向前移动一位,调用System.arraycopy()方法进行元素拷贝,最后将列表中最后一个元素赋值null,这里不需要担心此对象占用空间,因为GC会处理无引用对象。

    • remove(Object o)
      功能为删除ArrayList的指定元素,注意这里是以指定元素去删除列表中元素。实现方法稍有不同,首先会判断参数是否为null,如为null它并不会报错,因为存在列表中有元素为null的情况,这时开始遍历列表,移除找到的第一个值为null的元素;为不为null则遍历比较是否有相同元素,没有返回False,反之则移除,返回TRue,移除方法与上述 remove(int index)相同,在此不赘述。

    1.8 set()方法

    • set(int index, E element)
      功能就是把这个列表上某一个元素的值进行变更修改。首先检查修改的index下标是否合法,即检查下标是否越界,然后将列表中原index的值取出保存到oldValue中返回,将值设置为更新的新值。很普通的数组修改值实现,并无太大难度。

    1.8 get()方法

    • get(int index)
      功能为根据下标返回列表中对应元素。首先会检查下表是否合法,然后由于列表底层由数组实现,所以直接将下标对应值返回即可。
  • 相关阅读:
    试用第三方web推送GoEasy
    使用intellj idea 搭建本地开发环境
    一种基于struts2 拦截器 和 log4j的轻量级crm权限及行为跟踪方式
    Spring AOP声明式事务异常回滚 若干法则
    spring aop 切面测试
    centos 安装 mysql
    只是 换个方式,
    contrller 是 file's owners,
    色差,15,还是15 ,换了颜色 就显的小了,
    一块,分开,还是不分开 一个整体,
  • 原文地址:https://www.cnblogs.com/0427mybirthday/p/7536864.html
Copyright © 2020-2023  润新知