JDK集合源码之ArrayList解析(附带面试题举例)

JDK集合源码之ArrayList解析(附带面试题举例)

1、ArrayList继承体系

hbXRET.png

ArrayList又称动态数组,底层是基于数组实现的List,与数组的区别在于,其具备动态扩展的能力。从继承体系图中可以看出。

ArrayList:

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
	...
}
  • 实现了List、RandomAccess、Cloneable、java.io.Serializable等接口
  • 实现了List,具备基础的添加、删除、遍历等操作
  • 实现了RandomAccess,具备随机访问的能力
  • 实现了Seralizable,可以被序列化

2、ArrayList实现Cloneable、RandomAccess、Serializable接口

实现Cloneable接口,可以被浅拷贝

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

想要具体了解深拷贝和浅拷贝的朋友可以去看看这篇博客:https://www.cnblogs.com/gesh-code/p/15246798.html

实现了RandomAccess接口,可以提高随机访问列表的效率

ArrayList实现了RandomAccess接口,因此当执行随机访问列表的时候,效率要高于顺序访问列表的效率,我们来看一个例子:

@Test
public void test01(){
    ArrayList list=new ArrayList();
    for (int i = 0; i <= 99999; i++) { //向集合中添加十万条数据
        list.add(i);
    }
    //测试随机访问的效率:
    Long startTime=System.currentTimeMillis();
    for (int i = 0; i < list.size(); i++) { //随机访问
        //从集合中访问每一个元素
        list.get(i);
    }
    Long endTime=System.currentTimeMillis();
    System.out.println("随机访问执行所用的时间为:"+(endTime-startTime));
    //测试顺序访问的效率:
    startTime=System.currentTimeMillis();
    Iterator it=list.iterator(); //顺序访问,也可以使用增强for
    while (it.hasNext()){
        //从集合中访问每一个元素
        it.next();
    }
    endTime=System.currentTimeMillis();
    System.out.println("执行顺序访问所用时间:"+(endTime-startTime));
}

查看输出结果:

随机访问执行所用的时间为:1
执行顺序访问所用时间:4

可以看出实现RandomAccess接口的ArrayList进行随机访问的效率高于进行顺序访问的效率。

作为对比我们再来看一下未实现RandomAccess接口的LinkedList集合,测试随机访问和顺序访问列表的效率对比:

@Test
public void test02(){
    LinkedList list=new LinkedList();
    for (int i = 0; i <= 99999; i++) { //向集合中添加十万条数据
        list.add(i);
    }
    //测试随机访问的效率:
    Long startTime=System.currentTimeMillis();
    for (int i = 0; i < list.size(); i++) { //随机访问
        //从集合中访问每一个元素
        list.get(i);
    }
    Long endTime=System.currentTimeMillis();
    System.out.println("随机访问执行所用的时间为:"+(endTime-startTime));
    //测试顺序访问的效率:
    startTime=System.currentTimeMillis();
    Iterator it=list.iterator(); //顺序访问,也可以使用增强for
    while (it.hasNext()){
        //从集合中访问每一个元素
        it.next();
    }
    endTime=System.currentTimeMillis();
    System.out.println("执行顺序访问所用时间:"+(endTime-startTime));
}

查看输出结果:

随机访问执行所用的时间为:3732
执行顺序访问所用时间:1

由结果可得出结论,没有实现RandomAccess接口的LinkedList集合,测试随机访问的效率远远低于顺序访问。

3、ArrayList 属性

 /**
 * 默认容量为10
 */
private static final int DEFAULT_CAPACITY = 10;

/**
 * 空数组,如果传入的容量为0时使用
 */
private static final Object[] EMPTY_ELEMENTDATA = {};

/**
 * 默认空容量的数组,长度为10,传入容量的时候使用,添加第一个元素的时候
 * 会重新初始为默认容量大小
 */
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

/**
 * 集合中真正存储数据元素的数组容器
 */
transient Object[] elementData; // non-private to simplify nested class access

/**
 * 集合中元素的个数
 */
private int size;
  • DEFAULT_CAPACITY:集合的默认容量,默认为10,通过new ArrayList()创建List实例时的默认集合容量是10.
  • EMPTY_ELEMENTDATA:空数组,通过new ArrayList(0)创建List集合实例的时候用的是这个空数组。
  • DEFAULTCAPACITY_EMPTY_ELEMENTDATA:默认容量空数组,这种是通过new ArrayList()无参构造方法创建集合的时候用的是这个空数组,与EMPTY_ELEMENTDATA的区别是再添加第一个元素的时候使用这个空数组的会初始化为DEFAULT_CAPACITY(10)个元素。
  • elementData:存储数据元素的数组,使用transient修饰,该字段不被序列化。
  • size:存储数据元素的个数,elementData数组的长度并不是存储数据元素的个数。

4、ArrayList构造方法

ArrayList(int initialCapacity)有参构造方法

/**
 * 构造具有指定初始容量的空数组、
 * 传入初始容量,如果大于0就初始化elementData为对应大小,如果等于0就使用EMPTY_ELEMENTDATA空数组
 * @param initialCapacity
 */
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);
    }
}

ArrayList()空参构造方法

/**
 * 构造一个初始容量为10的空数组
 * 不传初始容量,初始化为DEFAULTCAPACITY_EMPTY_ELEMENTDATA空数组
 * 会再添加第一个元素的时候扩容为默认的大小,即10
 */
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

ArrayList(Collection c)有参构造方法

/**
 * 把传入集合的元素初始化到ArrayList中
 * @param c
 */
public ArrayList(Collection<? extends E> c) {
    //将构造方法中的集合参数转换成数组
    elementData = c.toArray();
    if ((size = elementData.length) != 0) {
        //检查c.toArray()返回的是不是Object[]类型,如果不是,重新拷贝成Object[].class类型
        if (elementData.getClass() != Object[].class)
            //数组的创建与拷贝
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    } else {
        //如果c是空的集合,则初始化为空数组EMPTY_ELEMENTDATA
        this.elementData = EMPTY_ELEMENTDATA;
    }
}

问题:为什么要检查c.toArray()返回的是不是Object[]类型,重新拷贝成Object[].class类型呢?

首先,我们都知道Object是java中的超级父类,所有类都间接或者直接继承于Object,接着我们来看一个例子:

public class ArrayListTest {
    class Father{

    }
    class Son extends Father{

    }
    class MyList extends ArrayList<String>{
        /**
         * 子类重写父类的方法,返回值可以不一样,但这里只能用数组类型
         * 换成Object就不行,应该算是java本身的bug
         * @return
         */
        @Override
        public String[] toArray() {
            //为了方便举例直接写死
            return new String[]{"a","b","c"};
        }
    }

    @Test
    public void test01(){
        Father[] fathers=new Son[]{};
        //输出结果:class [LArrayListTest$Son;
        System.out.println(fathers.getClass());

        List<String> list=new MyList();
        //输出结果:class [Ljava.lang.String;
        System.out.println(list.toArray().getClass());
    }
}

5.ArrayList相关操作方法

add(E e)添加元素到集合中

添加元素到末尾,平均时间复杂度为O(1):

/**
 * 添加元素到末尾,平均时间复杂度为O(1)
 * @param e
 * @return
 */
public boolean add(E e) {
    //每加入一个元素,minCacpacity大小+1,并检查是否需要扩容
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    //把元素插入到最后一位
    elementData[size++] = e;
    return true;
}
/**
 * 计算最小容量
 * @param elementData
 * @param minCapacity
 * @return
 */
private static int calculateCapacity(Object[] elementData, int minCapacity) {
    //如果是空数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        //返回DEFAULT_CAPACITY和minCapacity大的一方
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    return minCapacity;
}

/**
 * 检查是否需要扩容
 * @param minCapacity
 */
private void ensureCapacityInternal(int minCapacity) {
    ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}

//扩容
private void ensureExplicitCapacity(int minCapacity) {
    modCount++; //数组结构被修改的次数

    //存储元素的数据长度小于需要的最小容量的时候
    if (minCapacity - elementData.length > 0)
        //扩容
        grow(minCapacity);
}

private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

//真正扩容方法 增加增量以确保它至少可以容纳最小容量参数指定的元素数量
private void grow(int minCapacity) {
    //原来的容量
    int oldCapacity = elementData.length;
    //新容量为旧容量的1.5倍
    int newCapacity = oldCapacity + (oldCapacity >> 1);

    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    //如果新容量已经超过了数组的最大容量MAX_ARRAY_SIZE了,则使用最大容量MAX_ARRAY_SIZE,最大为MAX_VALUE
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    //以新容量拷贝出来一个新数组
    elementData = Arrays.copyOf(elementData, newCapacity);
}

//当扩容后的新容量大于MAX_ARRAY_SIZE的时候,保证使用最大容量
private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

执行流程:

  • 检查是否需要扩容
  • 如果elementData等于DEFAULTCAPACITY_EMPTY_ELEMENTDATA,则初始化容量为DEFAULT_CAPACITY;
  • 通过calculateCapacity方法计算所需要的最小容量,确定最小容量后继续调用ensureExplicitCapacity进行扩容
  • 真正执行扩容方法,grow()新容量是老容量的1.5倍(OldCapacity+(OldCapacity>>1)),如果加了这么多发现比需要的容量还小,则以需要的容量为准。
  • 创建新容量的数组并把老数组拷贝到新数组。

add(int index,E element)添加元素到指定位置

添加元素到指定位置,平均时间复杂度为O(n):

/**
 * 添加元素到指定位置,平均时间复杂度为O(n)
 * @param index 指定要插入的索引
 * @param element 要插入的元素
 */
public void add(int index, E element) {
    //检查下标是否越界
    rangeCheckForAdd(index);

    //检查是否需要扩容
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    //将index及其之后的元素往后挪一位,则index位置处就空出来了
    //进行了size-索引index次操作
    System.arraycopy(elementData, index, elementData, index + 1,
                     size - index);
    //将元素插入到index的位置
    elementData[index] = element;
    //元素数量增加1
    size++;
}
/**
 * 检查是否越界
 * @param index
 */
private void rangeCheckForAdd(int index) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

执行流程:

  • 检查索引是否越界
  • 检查是否需要扩容
  • 把插入索引位置后的元素都往后挪一位
  • 在插入索引位置放置插入的元素
  • 元素数量+1

addAll(Collection c)添加所有集合参数中的所有元素

求两个集合的并集:

/**
* 将集合c中所有的元素添加到当前ArrayList中
* @param c 要添加的集合
* @return
*/
public boolean addAll(Collection<? extends E> c) {
   //将集合c转化为数组
   Object[] a = c.toArray();
   int numNew = a.length;
   //检查是否需要扩容
   ensureCapacityInternal(size + numNew);  // Increments modCount
   //将集合c中的元素全部拷贝到数组的最后
   System.arraycopy(a, 0, elementData, size, numNew);
   //集合中元素个数的大小增加c的大小
   size += numNew;
   //如果c不为空就返回true,否则返回false
   return numNew != 0;
}

get(int index)获取指定索引位置的元素

获取指定索引位置的元素,时间复杂度为O(1)。

/**
 * 获取指定索引位置的元素
 * @param index 指定索引位置
 * @return
 */
public E get(int index) {
    //检查是否越界
    rangeCheck(index);

    //返回数组index位置的元素
    return elementData(index);
}
/**
 * 检查给定的索引是否在集合有效元素数量范围内
 * @param index 给定的索引
 */
private void rangeCheck(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

@SuppressWarnings("unchecked")
E elementData(int index) {
    return (E) elementData[index];
}

执行流程:

  • 检查索引是否越界,这里只检查是否越上界,如果越上界则抛出IndexOutOfBoundsException(outOfBoundsMsg(index));如果越下界抛出的是ArrayIndexOutOfBoundsException异常
  • 返回索引位置处的元素(要进行强转)

remove(int index)删除指定索引位置的元素

删除指定索引位置的元素,时间复杂度为O(N)。

/**
 * 删除指定索引位置的元素,时间复杂度为O(n)
 * @param index 指定的索引
 * @return
 */
public E remove(int index) {
    //检查是否越界
    rangeCheck(index);

    //集合底层数组结构修改次数+1
    modCount++;
    //获取index位置的元素
    E oldValue = elementData(index);
    //要移动的元素个数
    int numMoved = size - index - 1;
    if (numMoved > 0)
        //进行了size-索引-1次移动操作
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    //将最后一个元素删除,帮助GC
    elementData[--size] = null; // clear to let GC do its work

    //返回旧值(即被删除的值)
    return oldValue;
}

注意:从源码中得出,ArrayList删除元素的时候并没有扩容

remove(Object o)删除指定元素值的元素

删除指定元素值的元素,时间复杂度为O(n)。

/**
 * 删除指定元素值的元素,时间复杂度为O(n)
 * 要从此列表中删除的元素(如果存在的话)
 * @param o
 * @return
 */
public boolean remove(Object o) {
    if (o == null) {
        //遍历整个数组,找到元素第一次出现的位置,并将其快速删除
        for (int index = 0; index < size; index++)
            //如果要删除的元素为null,则以null进行比较,使用==
            if (elementData[index] == null) {
                fastRemove(index);
                return true;
            }
    } else {
        //遍历整个数组,找到元素第一次出现的位置,并将其快速删除
        for (int index = 0; index < size; index++)
            //如果要删除的元素不为null,则进行比较,使用equals()方法
            if (o.equals(elementData[index])) {
                fastRemove(index);
                return true;
            }
    }
    return false;
}

/**
 * 专用的remove方法,跳过边界检查,并且不返回删除的值
 * @param index
 */
private void fastRemove(int index) {
    //集合底层数组结构修改次数+1
    modCount++;
    //如果index不是最后一位,则将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
}

执行流程:

  • 找到第一个等于指定元素值的元素

  • 快速删除

    fastRemove(int index)相对于remove(int index)少了检查索引越界的操作,可见JDK一直在做性能优化

retainAll(Coolection c)求两个集合的交集

/**
 * 求两个集合的交集
 * @param c 集合对象
 * @return
 */
public boolean retainAll(Collection<?> c) {
    //集合对象c不能为null
    Objects.requireNonNull(c);
    //采用批量删除的方式,这时complement传入true,表示删除不包含在c中的元素
    return batchRemove(c, true);
}

/**
 * 批量删除元素
 * @param c 集合对象
 * @param complement 为true表示删除c中不包含的元素
 *        complement为false表示删除c中包含的元素
 * @return
 */
private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    /**
     * 使用读写两个指针同时遍历数组
     * 读指针每次自增1,写指针放入元素的时候才加1
     * 这样不需要额外的空间,只需要在原有的数组上操作就可以了
     */
    int r = 0, w = 0;
    boolean modified = false;
    try {
        for (; r < size; r++)
            //遍历整个数组,如果c中包含该元素,则把该元素放到写指针的位置(以complement为准)
            if (c.contains(elementData[r]) == complement)
                elementData[w++] = elementData[r];
    } finally {
        //正常来说r最后是等于size的,除非c.contains()抛出了异常
        if (r != size) {
            //如果c.contains()出现了异常,则把未读的元素都拷贝到写指针后
            System.arraycopy(elementData, r,
                             elementData, w,
                             size - r);
            w += size - r;
        }
        if (w != size) {
            //将写指针之后的元素置为空,帮助GC
            for (int i = w; i < size; i++)
                elementData[i] = null;
            modCount += size - w;
            //新大小等于写指针的位置(因为每写一次写指针就加1,所以新大小正好等于写指针的位置)
            size = w;
            modified = true;
        }
    }
    //有修改返回true
    return modified;
}

执行流程:

  • 遍历elementData数组
  • 如果元素在c中,则把这个元素添加到elementData数组的w位置并将w位置往后移一位
  • 遍历完之后,w之前的元素都是两者共有的,w之后(包含)的元素不说两者共有的
  • 将w之后(包含)的元素置为null,方便GC回收

removeAll(Collection c)求两个集合的单方向差集

求两个集合的单方向差集,只保留当前集合中不在c中的元素,不保留在c中不在当前集合中

/**
 * Removes from this list all of its elements that are contained in the
 * specified collection.
 * 从此集合中删除指定的集合中包含的所有元素。
 * 
 * @param c collection containing elements to be removed from this list
 * @return {@code true} if this list changed as a result of the call
 * @throws ClassCastException   if the class of an element of this list
 *                              is incompatible with the specified collection
 *                              (<a href="Collection.html#optional-restrictions">optional</a>)
 * @throws NullPointerException if this list contains a null element and the
 *                              specified collection does not permit null elements
 *                              (<a href="Collection.html#optional-restrictions">optional</a>),
 *                              or if the specified collection is null
 * @see Collection#contains(Object)
 */
public boolean removeAll(Collection<?> c) {
    // 集合c不能为空
    Objects.requireNonNull(c);
    // 同样调用批量删除方法,这时complement传入false,表示删除包含在c中的元素
    return batchRemove(c, false);
}

与retainAll(Collection c)方法类似,只是这里保留的是不在c中的元素。

6、扩展知识

ArrayList所使用的toString()方法分析:

我们都知道ArrayList集合是可以直接使用toString()方法的,那么我们来挖一下ArrayList的toString()方法是如何实现的:

在ArrayList源码中并没有直接的toString()方法,我们需要到其父类AbstractList的父类AbstractCollection中寻找:

public String toString() {
    Iterator<E> it = iterator(); //获取迭代器
    if (! it.hasNext()) //如果为空直接返回
        return "[]";

    //StringBuilder进行字符串拼接
    StringBuilder sb = new StringBuilder();
    sb.append('[');
    for (;;) { //无限循环
        E e = it.next(); //迭代器next方法去元素,并将其光标后移
        sb.append(e == this ? "(this Collection)" : e);
        if (! it.hasNext())
            return sb.append(']').toString(); //没有元素了。则拼接右括号
        sb.append(',').append(' '); //还有元素存在
    }
}
总结:
(1)ArrayList内部使用数组存储元素,当数组长度不够的时候进行扩容,每次加一半的空间,ArrayList不会进行缩容。
(2)ArrayList支持随机访问,通过索引访问元素极快,时间复杂度为O(1)
(3)ArrayList添加元素到尾部极快,平均时间复杂度为O(1)
(4)ArrayList添加元素到中间比较慢,因为要搬移元素,平均时间复杂度为O(n)
(5)ArrayList从尾部删除元素极快,时间复杂度为O(1)
(6)ArrayList从中间删除元素比较慢,因为要搬移元素,平均时间复杂度为O(n)
(7)ArrayList支持求并集,调用addAll(Collection c)方法即可
(8)ArrayList支持求交集,调用retainAll(Collection c)方法即可
(9)ArrayList支持求单向差集,调用removeAll(Collection c)方法即可

答疑问题:elementData设置成了transient,那么ArrayList是怎么把元素序列化的呢?

/**
 * 将ArrayList实例的状态保存到流中(对其进行序列化)
 * @param s
 * @throws java.io.IOException
 */
private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException{
    //防止序列化期间有修改
    int expectedModCount = modCount;
    //写出非transient非static属性(会写出size属性)
    s.defaultWriteObject();

    //写出元素个数
    s.writeInt(size);

    //依次写出元素
    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;

    //读入非transient非static属性(会读取size属性)
    s.defaultReadObject();

    // 读入元素个数,没什么用,只是因为写出的时候写了size属性,读入的时候也要按照顺序来读
    s.readInt(); // ignored

    if (size > 0) {
        //计算最小容量
        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();
        }
    }
}

查看writeObject()方法可知,先调用s.defaultWriteObject() 方法,再把size写入流中,再把元素一个一个的写入到流中。

一般地,只要实现了Serializable接口即可自动序列化,writeObject()和readObject()是为了自己控制序列化地方式,这两个方式必须声明为private,再java.io.ObjectStreamClass#getPrivateMethod()方法中通过反射获取到writeObject()这个方法。

在ArrayList地writeObject()方法中先调用了s.defaultWriteObject()方法,这个方法是写入非static非transien地属性,在ArrayList中也就是size属性。同样的,在readObject()中先调用了s.defaultyReadObject()方法解析出了size属性。

elementData定义为transient的优势,自己根据size序列化真实的元素,而不是根据数组的长度序列化元素,减少了空间的占用。

7、ArrayList相关面试题

7.1、ArrayList如何进行扩容?

第一次扩容10,以后每次都扩容原容量的1.5倍,扩容通过位运算右移动一位

7.2、ArrayList频繁扩容导致添加新跟那个急剧下降,如何处理?

@Test
public void test06(){
    //ArrayList频繁扩容导致添加性能急剧下降,如何处理?
    //案例如下:
    ArrayList list=new ArrayList();
    long startTime=System.currentTimeMillis();
    //添加100w条数据到集合中
    for (int i = 0; i < 10000000; i++) {
        list.add(i);
    }
    long endTime=System.currentTimeMillis();
    System.out.println("优化之前,添加100w数据用时:"+(endTime-startTime));
    System.out.println("---------------下边是解决方案-------------------");
    ArrayList list1=new ArrayList(1000000);
    startTime=System.currentTimeMillis();
    //添加100w数据到集合中
    for (int i = 0; i < 10000000; i++) {
        list1.add(i);
    }
    endTime=System.currentTimeMillis();
    System.out.println("优化之后,添加100w条数据用时:" + (endTime - startTime));
}

输出结果:

优化之前,添加100w数据用时:2522
---------------下边是解决方案-------------------
优化之后,添加100w条数据用时:863

可以看出,如果在大量数据需要添加到集合中的时候,提前定义ArrayList集合的初始容量,从而不用花费大量时间在自动扩容上。

7.3、ArrayList插入或者删除元素是否一定比LinkedList慢?

从二者底层数据结构来说:

  • ArrayList是实现了基于动态数组的数据结构
  • LinkedList是基于链表的数据结构。

效率对比:

  • 首部插入:LinkedList首部插入数据很快,因为只需要修改插入元素前面节点的prev值和next值集合。ArrayList首部插入数据慢,因为数组赋值的方式移位耗时多。
  • 中间插入:LinkedList中间插入数据慢,因为遍历链表指针(二分查找)耗时多;ArrayList中间插入数据快,因为定位插入元素位置的速度快,移位操作的元素没那么多。
  • 尾部插入:LinkedList尾部插入数据慢,因为遍历链表指针(二分查找)耗时多;ArrayList尾部插入数据快,为定位插入元素位置的速度快,操作后移位操作的数据量较少。

总结:

  • 在集合里面插入元素速度比对结果是:首部插入,LinkedList更快;中间和尾部插入,ArrayList更快。
  • 在集合里面删除元素类似,首部删除,LinkedList更快;中间和尾部删除,ArrayList更快。

因此,数据量不大的集合,主要进行插入、删除操作,建议使用LinkedList;数据量大的集合,使用ArrayList就可以了,不仅查询速度快,并且插入和删除效率也相对较高。

7.4、ArrayList是线程安全的吗?

答案肯定是否定的,我们来看一个例子:

首先新建一个线程任务类:

public class CollectionTask implements Runnable {
    //共享集合
    private List<String> list;

    public CollectionTask(List<String> list) {
        this.list = list;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //把当前线程名字加入到集合中
        list.add(Thread.currentThread().getName());
    }
}

测试代码:

@Test
public void test03() throws InterruptedException {
    //创建集合
    List<String> list=new ArrayList<>();
    //创建线程任务
    CollectionTask collectionTask=new CollectionTask(list);
    //开启50个任务
    for (int i = 0; i < 50; i++) {
        new Thread(collectionTask).start();
    }
    //确保子线程执行完毕
    Thread.sleep(3000);
    /**
     * 如果ArrayList是线程安全的,则遍历集合可以得到50条数据
     * 打印集合长度为50
     * 否则说明其不说线程安全的
     */
    for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i));
    }
    System.out.println("--------------------------------");
    System.out.println("集合长度:"+list.size());
}
}

输出:

null
null
Thread-1
Thread-3
Thread-5
Thread-7
Thread-4
Thread-30
Thread-33
Thread-32
Thread-31
Thread-28
Thread-29
Thread-27
Thread-25
Thread-26
Thread-23
Thread-22
Thread-24
Thread-21
Thread-20
Thread-17
Thread-16
Thread-19
Thread-18
Thread-13
Thread-12
Thread-15
Thread-9
Thread-8
Thread-14
Thread-11
Thread-10
null
Thread-48
Thread-45
Thread-44
Thread-41
Thread-40
Thread-37
Thread-36
Thread-47
Thread-46
Thread-43
Thread-42
Thread-39
Thread-38
Thread-35
Thread-34
--------------------------------
集合长度:49

因此,得出结论,ArrayList并不是线程安全的集合!如果需要保证线程安全,建议使用Vector集合,其是线程安全的,但是相对于ArrayLisyt来说,效率较低。

Vector相对于ArrayList之所以是线程安全的,就在于其add()为集合添加元素的方法:

// 可以看出Vector的add方法加上了synchronized 同步关键字
public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
}

​ 除了Vector集合外,还可以使用为如下方式:

List<String> list = new ArrayList<>();
List<String> synchronizedList = Collections.synchronizedList(list);

这样得到的synchronized也是线程安全的!

注意:什么情况下不用给ArrayList加同步锁呢?

  • 第一:在单线程的情况下不需要加锁,为效率问题考虑!
  • 第二,当ArrayList作为局部变量的时候不需要加锁,因为局部变量属于某一线程,而我们把上述例子中是把ArrayLIst作为成员变量来使用,成员变量的集合是需要被所有线程共享的,这是需要加锁!

7.5、如何赋值某个ArrayList到另外一个Arraylist中去呢?你能列举几种?

  • 使用clone()方法,因为ArrayList方法实现了Cloneable接口,可以被克隆
  • 使用ArrayList构造方法,ArrayList(Collection<? extends E> c)
  • 使用addAll(Collection<? extends E> c)
  • 自己写一个循环去一个一个add

7.6 、ArrayList如何做到并发修改,而不出现并发修改异常?

问题:已知成员变量集合存储N多用户名称,在多线程环境下,使用迭代器在读取集合数据的同时,如何保证还可以正常地写入数据到集合?

新建一个线程任务类:

/**
 * @Description: 线程任务类,使用ArrayList在多线程环境下,修改集合数据,
 * 且不出现并发修改异常
 */
public class CollectionThread implements Runnable{
    private static ArrayList<String> list = new ArrayList<>();
    static {
        list.add("Jack");
        list.add("Amy");
        list.add("Lucy");
    }

    @Override
    public void run() {
        for (String value : list){
            System.out.println(value);
            // 在读取数据的同时又向集合写入数据
            list.add("Coco");// 会出现并发修改异常
        }
    }
}

测试在多线程环境下读取共享集合数据地同时向其写入:

/**
 * @Description: 面试问题:
 * 已知成员变量集合存储N多用户名称,在多线程的环境下,使用迭代器在读取集合数据的同时,
 * 如何保证还可以正常的写入数据到集合?
 */
public class Test03 {
    public static void main(String[] args) {
        // 创建线程任务
        CollectionThread collectionThread = new CollectionThread();

        // 开启10条线程
        for (int i = 0; i < 10; i++) {
            new Thread(collectionThread).start();
        }
    }
}

测试结果:

Jack
Jack
Jack
Jack
Jack
Jack
Jack
Jack
Jack
Jack
Exception in thread "Thread-0" Exception in thread "Thread-1" Exception in thread "Thread-4" Exception in thread "Thread-5" Exception in thread "Thread-8" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)
	at com.haust.list.CollectionThread.run(CollectionThread.java:21)
	at java.lang.Thread.run(Thread.java:748)
Exception in thread "Thread-9" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)
	at com.haust.list.CollectionThread.run(CollectionThread.java:21)
	at java.lang.Thread.run(Thread.java:748)
Exception in thread "Thread-2" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)
	at com.haust.list.CollectionThread.run(CollectionThread.java:21)
	at java.lang.Thread.run(Thread.java:748)
java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)
	at com.haust.list.CollectionThread.run(CollectionThread.java:21)
	at java.lang.Thread.run(Thread.java:748)
java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)
	at com.haust.list.CollectionThread.run(CollectionThread.java:21)
	at java.lang.Thread.run(Thread.java:748)
java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)
	at com.haust.list.CollectionThread.run(CollectionThread.java:21)
	at java.lang.Thread.run(Thread.java:748)
java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)
	at com.haust.list.CollectionThread.run(CollectionThread.java:21)
	at java.lang.Thread.run(Thread.java:748)
Exception in thread "Thread-7" Exception in thread "Thread-6" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)
	at com.haust.list.CollectionThread.run(CollectionThread.java:21)
	at java.lang.Thread.run(Thread.java:748)
Exception in thread "Thread-3" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)
	at com.haust.list.CollectionThread.run(CollectionThread.java:21)
	at java.lang.Thread.run(Thread.java:748)
java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)
	at com.haust.list.CollectionThread.run(CollectionThread.java:21)
	at java.lang.Thread.run(Thread.java:748)

出现并发修改异常,为解决此问题呢,java引入了一个可以保证读和写都是线程安全地集合(读写分离集合):CopyonWriteArrayList

所以解决方案就是:


// private static ArrayList<String> list = new ArrayList<>();
// 使用读写分离集合替换掉原来的ArrayList
private static CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
static {
    list.add("Jack");
    list.add("Amy");
    list.add("Lucy");
}
@Override
public void run() {
    for (String value : list){
        System.out.println(value);
        // 在读取数据的同时又向集合写入数据
        list.add("Coco");// 会出现并发修改异常
    }
}
原文地址:https://www.cnblogs.com/gesh-code/p/15315267.html