Java集合-ArrayList 详解

ArrayList 概述

  1. ArrayList的底层实现就是一个动态数组,他的容量大小可以自动扩展。
  2. ArrayList不是线程安全的,只能用在单线程环境下,多线程环境下可以考虑用Collections.synchronizedList(List l)函数返回一个线程安全的ArrayList类,也可以使用concurrent并发包下的CopyOnWriteArrayList类。

ArrayList 详解

1.私有属性

/**
 * Default initial capacity.//初始化数组时默认长度
 */
private static final int DEFAULT_CAPACITY = 10;

 /**
  * 默认大小的空实例。我们区分EMPTY_ELEMENTDATA是在第一个元素添加的时候
  * Shared empty array instance used for default sized empty instances. We
  * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
  * first element is added.
  */
 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

 /**
  * The array buffer into which the elements of the ArrayList are stored.
  * The capacity of the ArrayList is the length of this array buffer. Any
  * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.存放元素的数组
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains). 数组大小
     *
     * @serial
     */
    private int size;

Java的serialization提供了一种持久化对象实例的机制。当持久化对象时,可能有一个特殊的对象数据成员,我们不想用serialization机制来保存它。为了在一个特定对象的一个域上关闭serialization,可以在这个域前加上关键字transient。

2.最大长度

  ArrayList最大长度 是2^31-1-8.(具体的自己也没有搞的太清楚,看注释说可能导致OutOfMemoryError,请求的数组大小超过VM限制)

/**
 * The maximum size of array to allocate.
 * Some VMs reserve some header words in an array.
 * Attempts to allocate larger arrays may result in
 * OutOfMemoryError: Requested array size exceeds VM limit
 */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

3.构造函数

   ArrayList提供了三种方式的构造器,可以构造一个默认初始容量为0的空列表(在第一次add的时候容量会变为10)、构造一个指定初始容量的空列表以及构造一个包含指定collection的元素的列表,这些元素按照该collection的迭代器返回它们的顺序排列的。

/**
 * 注意:在使用无参初始化集合时,初始化集合的容量仍为0。只有在第一次添加元素的时候。动态数组的容量大小才会是默认的10。
 * 构造一个空列表的初始容量10。
 */
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
 * 构造一个与指定初始容量的空列表。
 *
 * @param  初始化默认容量
 */
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);
    }
 }
 /**
  * 构造一个包含指定集合的元素的列表
  *
  * @param c 集合
  */
 public ArrayList(Collection<? extends E> c) {
     //将指定的集合转换为数组,并赋值
     elementData = c.toArray();
    //判断数组不为空
     if ((size = elementData.length) != 0) {
         //如果elementData不是数组对象的话,重新复制数组
         if (elementData.getClass() != Object[].class)
             elementData = Arrays.copyOf(elementData, size, Object[].class);
         } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
 }

4.分配数组容量

   使用的无参构造函数创建的ArrayList的大小默认是0,只有在第一次add元素的时候,动态数组的容量才为默认值10.如果添加的元素大于数组的容量,内部的数组会进行动态扩容,扩容后大小是扩容前的1.5倍。

/**
 * 增加ArrayList的容量,确保它可以容纳最低容量参数指定的元素的个数。
 * @param   minCapacity   需要的最小容量
 */
public void ensureCapacity(int minCapacity) {
    //如果存放元素的数组与默认的空数组不是同一个对象时,返回0,否则返回默认只
    int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            ? 0
            : 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是AbstractList的属性。已从结构上修改 此列表的次数。
    modCount++;
    //所需的最小容量大于数组的容量
    if (minCapacity - elementData.length > 0)
            grow(minCapacity);
 }
 /**
  * 增加容量以确保它至少能够容纳最小容量参数指定的元素数量。
  *
  * @param minCapacity the desired minimum capacity
  */
 private void grow(int minCapacity) {
    int oldCapacity = elementData.length;
    //增加原来容量的1/2
    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;
    }

modCoundt:modCount是AbstractList的属性。已从结构上修改 此列表的次数。从结构上修改是指更改列表的大小,或者打乱列表,从而使正在进行的迭代产生错误的结果。 在ArrayList的所有涉及结构变化的方法中都增加modCount的值,包括:add()、remove()、addAll()、removeRange()及clear()方法。这些方法每调用一次,modCount的值就加1。

5.ArrayList常用的api

  ArrayList一些比较常用的api

1.  add(E e);//将指定的元素追加到此列表的末尾。
2.  add(int index, E element);//将指定的元素插入这个列表的指定位置
   /** 
    * @param index 指定元素要插入的索引
    * @param element 要插入的元素
    */
    public void add(int index, E element) {
        //越界判断
        rangeCheckForAdd(index);
        //申请动态数组容量
        ensureCapacityInternal(size + 1);
        //将角标大于等于index,全部向后移动
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        //插入元素
        elementData[index] = element;
        size++;
    }
3. addAll(Collection<? extends E> c);//将集合添加到当前集合内
4. addAll(int index, Collection<? extends E> c);//将集合添加到当前集合指定的角标内 
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);
        //将集合转化为数组
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);
        //需要一定的第一个角标
        int numMoved = size - index;
        if (numMoved > 0)
            //移动数组
            System.arraycopy(elementData, index, elementData, index + numNew,numMoved);
        //将制定的数组copy到指定位置
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }
5.  size();//获取集合的大小
6.  isEmpty();//判读集合的size是否等于0
7.  indexOf(Object o);//指定的元素是否存在集合内,存在返回角标,不存在返回-1; 
        public int indexOf(Object o) {
            //因为动态数组没有放满的话,有null对象
            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;
        }
8.  lastIndexOf(Object o);//从后面遍历指定元素是否存在集合
9.  contains(Object o);//集合是否存在指定的元素,内部就是判断index大于0
10. get(int index);//获取指定位置元素对象
11. set(int index, E element);//将指定位置的元素替换为指定的元素
12. remove(int index);//删除该列表中指定位置的元素。后面的元素整体向前移动
       /** 
        * @param index 指定的角标
        * @return 返回移除的对象
        */
        public E remove(int index) {
            rangeCheck(index);
            modCount++;
            E oldValue = elementData(index);
            //需要移动的数量
            int numMoved = size - index - 1;
            if (numMoved > 0)
                //将index+1 的
                System.arraycopy(elementData, index+1, elementData, index, numMoved);
            //gc回收资源
            elementData[--size] = null; 
            return oldValue;
        }
13. remove(Object o);//移除指定的元素  
        /** 
         * @param o 指定的元素
         * @return true 如果此列表包含指定的元素
         */
        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;
        }
       /**
        * 私有删除方法,跳过边界检查(与remove(int index)的区别就是没有进行边界检查)
        */
       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; 
        }
12. clear();//清除集合所有元素
13. retainAll(Collection<?> c);//保留指定的元素,其他的全部移除(取交集)
14. removeAll(Collection<?> c);//移除指定的元素集合(取补集)
        /**
         *  @param c 操作此集合的元素
         *  @param complement 标识此方法是移除或保留指定集合的元素 true 保留当前集合与指定集合的交集(retainAll)  false 保留当前集合与指定集合的补集集(removeAll)
         */
         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++)
                     //根据complement的值,决定取补集还是交集
                     if (c.contains(elementData[r]) == complement)
                         elementData[w++] = elementData[r];
                 } finally {
                     //因为contains会抛出异常,保留与AbstractCollection的行为兼容性
                     if (r != size) {
                         System.arraycopy(elementData, r,elementData, w,size - r);
                          w += size - r;
                      }
                      if (w != size) {
                          for (int i = w; i < size; i++)
                              elementData[i] = null;
                              modCount += size - w;
                              size = w;
                              modified = true;
                          }
                      }
                   return modified;
                }

15. toArray();//将集合转化为数组
16. toArray(T[] a);//方法返回一个包含所有在此列表中正确的序列中的元素(从第一个到最后一个元素)数组
    /**
     * @param a 要存储列表的元素的阵列,如果它足够大; 否则,为此目的分配相同运行时类型的新数组。
     * @return 一个包含列表元素的数组
     */
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        //指定的数组大小小于集合的大小
        if (a.length < size)
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

6.迭代器Iterator和ListIterator

6.1 ArrayList的Iterator

  在ArrayList内部通过iterator()获取Iterator对象。因为iterator()方法初始化了Itr对象。下面我们来看下Itr内部类的源码。

/**
 * AbstractList.Itr的优化版本
 */
 private class Itr implements Iterator<E> {
    int cursor;       // 要返回的下一个元素的索引
    int lastRet = -1; // 返回的最后一个元素的索引,如果没有这样的话返回-1
    int expectedModCount = modCount;

    //判断集合是否发生变化
    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }

    //判断是否有下一个
    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];
    }

    //移除当前指针下的元素,并将expectedModCount重新赋值(否则后续操作会抛异常)**注意:如果你没有调用next或者联系移除时会报错的**
    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") java 1.8使用lambda表达式遍历集合
    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++]);
        }
        // 在迭代结束时更新一次以减少堆写入流量
        cursor = i;
        lastRet = i - 1;
        checkForComodification();
    }
}
6.3 ArrayList的ListIterator

  在ArrayList内部有两种方式获取ListIterator对象。分别是listIterator()、listIterator(int index)两种方式。listIterator()方法内部调用的是listIterator(0),所以我们只需要关注listIterator(int index)的实现即可。

//内部初始化了一个ListItr,并设置迭代器的初始化角标
public ListIterator<E> listIterator(int index) {
    if (index < 0 || index > size)
        throw new IndexOutOfBoundsException("Index: "+index);
    return new ListItr(index);
}

  下面我们来看下ListItr的内部实现。因为ListItr继承Itr。这里就只写不同之出。

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

    //获取指针对应的元素,同时向前移动指针  **注意:这个返回的和next返回的是有区别的**
    @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];
    }

    //设置元素 注意事项:见6.4
    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();
        }
    }
}
6.3 Iterator和ListIterator的区别
  • 相同处
  • ListIterator和Iterator都有hasNext()和next()方法,可以实现顺序向后遍历。
  • 都又remove(),都能移除元素
  • 不同处
  • ListIterator有add()方法,可以向List中添加对象
  • ListIterator有hasPrevious()和previous()方法,可以实现逆向(顺序向前)遍历。
  • ListIterator可以定位当前的索引位置,nextIndex()和previousIndex()可以实现。
  • ListIterator可以实现对象的修改,set()方法可以实现。
6.4 使用Iterator和ListIterator需要注意的事项
  1. remove()的限制
    ① Iterator: Iterator必须调用next()一次后,以为Iterator初始化时 lastRet为-1。remove也不能连续调用,因为每调用一次remove方法时lastRet就会重新被赋值为-1.
    ② ListIterator: ListIterator必须调用过next或previous,调用此方法会报错,因为lastRet 初始化为为 0。当用过迭代器的remove和add也会出现类似的错误。因为在移除的时候lastRet 会被重新赋值为-1
  2. ListIterator.set()的限制
      ListIterator必须调用过next或previous,调用此方法会报错,因为lastRet 初始化为为 0。当用过迭代器的remove和add也会出现类似的错误。因为在移除的时候lastRet 会被重新赋值为-1