一、ArrayList简介

ArrayList的内部实现了动态数组,提供了动态的增加和减少元素,继承AbstractList类,并且实现了List、RandomAccess、Cloneable和java.io.Serializable接口。ArrayList是一个数组队列,提供添加、删除、修改和遍历元素的功能。因为实现RandomAccess接口,提供了随机访问的功能。现了Cloneable接口,即覆盖了函数clone(),能被克隆。现java.io.Serializable接口,这意味着ArrayList支持序列化。ArrayList不是线程安全的,建议在单线程中访问。
ArrayList有三个构造方法,定义如下:

//创建给定初始化大小的ArrayList
public ArrayList(int initialCapacity) {}
//默认无参构造方法创建的ArrayList
public ArrayList() {}
//创建给定初始化集合c的ArrayList
public ArrayList(Collection<? extends E> c) {}

二、源码分析

ArrayList是通过动态数组实现的,下面通过源码分析ArrayList的实现:

1、ArrayList主要源码分析

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
   
    /**
     * 默认初始化大小
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 空数组实例
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 判断是否为第一次添加元素
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * ArrayList保存元素数据,通过elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA 来判断是否是第一次添加元素
     */
    transient Object[] elementData;

    /**
     * ArrayList的实际大小
     */
    private int size;

    /**
     * 创建大小为initialCapacity的空ArrayList
     */
    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的list
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * 通过集合c创建list
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException 如果c为nulll,有空指针异常
     */
    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;
        }
    }

    /**
     * 缩小list容量为当前真实大小
     */
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

    //外部调用方法,调整容量,确保list不会越界
    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 static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
     
         //内部调用方法,调整容量,确保list不会越界
    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

         //扩展容量
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // 如果最小容量大于数组大小,进行数组扩展
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /**
     * 数组容量的最大值。部分虚拟机限制,大于MAX_ARRAY_SIZE,会导致OutOfMemoryError
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 数组按照1.5倍增加,如果增加后的值小于minCapacity,按照minCapacity增加
     * 
     */
    private void grow(int minCapacity) {
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;

           // 是否大于最大值
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

         //如果扩展容量大于最大值,按照最大值扩展
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0)
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

    /**
     * 返回list实际大小
     */
    public int size() {
        return size;
    }

    /**
     * 如果实际大小为0,返回true.
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 返回元素是否存在,indexOf(o)方法返回-1表示不存在.
     */
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    /**
     * 返回元素的下标,-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;
    }

    /**
     * 返回最后一个元素o的下标
     */
    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;
    }

    /**
     * copy一个list对象
     */
    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);
        }
    }

    /**
     * 将list转换为对象
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /**
     * 将list转换为对应类型的数组,如果数组大小小于size,通过Arrays.copyOf转换,如果大于System.arraycopy转换
     */
    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;
    }

    /**
     *  在list中添加一个元素
     */
    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!!
         //index之后的元素后移
        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);
        //将最后一个对象置空,便于GC
        elementData[--size] = null; 

        return oldValue;
    }

    /**
     * 根据指定的元素移除,调用fastRemove(index)方法
     */
    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
    }

    /**
     * 清除所有元素,size赋值0,
     */
    public void clear() {
        modCount++;

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

        size = 0;
    }

    /**
     * 将集合c中的元素添加到list中
     */
    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;
    }

    /**
     * 将集合c中的元素添加到index开始的位置,原index之后的元素后移
     */
    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;
    }

    /**
     * 删除集合c中所有元素,首选检查c是否为空,调用batchRemove(c, false)方法
     */
    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

    /**
     * 保留给定集合的元素,删除其他的
     *
     */
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

         /**
     * 根据complement判断是删除还是保留给定的集合元素
     *
     */
    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;
            }
             //把w下标后的数据删除
            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;
    }

    /**
     * 将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();
        }
    }

    /**
     * 从流中读取创建一个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
            int capacity = calculateCapacity(elementData, size);
            SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, 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();
            }
        }
    }

    /**
     * 返回一个以index开始的ListIterator迭代器
     */
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    /**
     * 返回从0开始的ListIterator迭代器
     */
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    /**
     * 返回Iterator迭代器
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * 定义一个基于AbstractList.Itr优化后的迭代器内部类,后面详细分析
     */
    private class Itr implements Iterator<E> {}

    /**
     * 定义一个基于 AbstractList.ListItr优化后的迭代器内部类,后面详细分析
     */
    private class ListItr extends Itr implements ListIterator<E> {}

    /**
     *返回一个从fromIndex到toIndex的子list
     */
    public List<E> subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, 0, fromIndex, toIndex);
    }
          //检查获取子list的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 + ")");
    }
         //子list内部类
    private class SubList extends AbstractList<E> implements RandomAccess {}

    @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> {  }

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

2、Itr和ListItr源码分析

上面分析了ArrayList源码,其中Itr和ListItr这两个内部类没有详细介绍。Itr和ListItr在AbstractList中有实现,在ArrayList对其进行了优化。下面进行详细介绍:

  • Itr

Itr实现了Iterator接口,源码如下:

private class Itr implements Iterator<E> {
         //下一个元素的下标          
        int cursor;       // index of next element to return
         //最后返回元素的下标,如果不存在,返回-1
        int lastRet = -1; 

     /**
      * 每个迭代器保存一个expectedModCount ,来记录这个迭代器对对象进行结构性修改的次数。
      * 每次迭代器进结构性修改的时候都将expectedModCount 和modCount进行对比
      * 如果两种相等则说明没有其他迭代器修改了对象,可以进行。如果不相等则说明有迭代进行了修改,立刻抛出异常
      */
        int expectedModCount = modCount;

        Itr() {}
        //下一个元素下标不等于size,表示还有下一个元素
        public boolean hasNext() {
            return cursor != size;
        }

        //获取到下一个元素
        public E next() {
            //检查其他迭代器对list是否有修改
            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();
        }
    }
  • ListItr

ListItr继承自Itr,并且实现了ListIterator接口,源码如下:

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

三、使用示例

1、ArrayList的四种遍历方式

jdk 1.8以前的集合list遍历支持三种方式,在1.8中增加了java 8 forEach方法,下面分别分析这四种遍历方式以及效率:

public class ArrayListIteratorTest {
    
        public static void main(String[] args) {
    
            List list = new ArrayList();
            for (int i = 0; i < 1000000 ; i++) {
                list.add(i);
            }
    
            iteratorTest(list);
    
            foreashITest(list);
    
            foreashTest(list);
    
            java8ForeashTest(list);
    
    
        }
    
        /**
         * 通过迭代器遍历
         * @param list
         */
        static void iteratorTest(List list){
            long startTime;
            long endTime;
            startTime = System.currentTimeMillis();
            Iterator iterator = list.iterator();
            while (iterator.hasNext()){
                iterator.next();
            }
            endTime = System.currentTimeMillis();
            System.out.println("Iterator time :" + (endTime - startTime));
        }
    
        /**
         * 通过索引遍历
         * @param list
         */
        static void foreashITest(List list){
            long startTime;
            long endTime;
            startTime = System.currentTimeMillis();
            for (int i = 0, length = list.size(); i < length; i++) {
                list.get(i);
            }
            endTime = System.currentTimeMillis();
            System.out.println("fori time :" + (endTime - startTime));
        }
    
        /**
         * 通过foreash遍历
         * @param list
         */
        static void foreashTest(List list){
            long startTime;
            long endTime;
            startTime = System.currentTimeMillis();
            for (Object l: list) {
    
            }
            endTime = System.currentTimeMillis();
            System.out.println("foreash time :" + (endTime - startTime));
        }
    
        /**
         * 通过java 8 中提供的foreash遍历
         * @param list
         */
        static void java8ForeashTest(List list){
            long startTime;
            long endTime;
            startTime = System.currentTimeMillis();
            list.forEach(l->{});
            endTime = System.currentTimeMillis();
            System.out.println("java 8 foreash time :" + (endTime - startTime));
        }
    }

以上代码运行后的结果如下:

clipboard.png

从运行结果看,foreash运行效率最高,java 8 中的foreash运行效率最差。

2、toArray()方法的使用

ArrayList中提供了连个方法将list转换为数组,分别是Object[] toArray()和<T> T[] toArray(T[] a)。调用第一个方法会有抛出“java.lang.ClassCastException”异常的情况,下面通过具体示例演示:

public class ArrayListToArraysTest {

    public static void main(String[] args) {
        List<Dog> list = new ArrayList<>();
        Dog dog1 = new Dog();
        Dog dog2 = new Dog();

        list.add(dog1);
        list.add(dog2);
    //此处会抛出异常
        Dog[] dogs1 = (Dog[]) list.toArray();
        System.out.println(Arrays.toString(dogs1));

        Dog[] dogs2 = new Dog[list.size()];
        dogs2 = list.toArray(dogs2);

        System.out.println(Arrays.toString(dogs2));
    }

    private static class Dog{
        private String name;

        private String color;


        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }
    }
}

3、fail-fast机制

当某一个线程A通过iterator去遍历某集合的过程中,若该集合的内容被其他线程所改变了;那么线程A访问集合时,就会抛出ConcurrentModificationException异常,产生fail-fast事件。
Fail-fast示例如下:

public class ArrayListFailFastTest {
        private static List list = new ArrayList();
        public static void main(String[] args) {
    
            Thread t1 = new Thread(new ThreadTest(),"t1");
            Thread t2 = new Thread(new ThreadTest(), "t2");
            t1.start();
            t2.start();
        }
    
        private static class ThreadTest implements Runnable{
            @Override
            public void run() {
                for (int i = 0; i < 20; i++) {
                    list.add(i);
                }
                Iterator iterator = list.iterator();
                while (iterator.hasNext()){
                    System.out.print(iterator.next() + " ");
                }
            }
        }
    
    }

clipboard.png

可以看出,在多线程下,通过iterator去遍历某集合,会抛ConcurrentModificationException异常。

四、总结

在本章中,分析了ArrayList集合。ArrayList的内部是通过动态数组存储数据的,默认初始大小是10,在jdk1.8中,默认构造方法创建对象,默认的数组为空,当第一次添加元素时,设置数组大小为10。在调整数组大小时,默认是增加原数组的1.5倍,如果传入的最小扩展数大于增加1.5倍后的大小,则按照此最小扩展数扩展,否则按照默认扩展。


zhzhd
16 声望5 粉丝