ArrayList类源码阅读

一、简介

ArrayList 位于java.util包中,使我们经常使用到的一个集合对象。

  • ArrayList是可调整大小的数组列表接口。实现所有可选的列表操作,并允许所有元素,元素也可以重复,包括null;
  • 除了实现List接口外,这个类还提供了操作数组大小的方法,该数组在内部用于存储列表;
  • ArrayList类似Vector,只是是非同步的;
  • 当元素被添加到ArrayList中时,容量自动增长(自动扩容机制)
  • 防止意外对列表的非同步访问: List list = Collections.synchronizedList(new ArrayList(...));
  •  
  • ArrayList继承了AbstractList<E>抽象类,实现了 List<E>, RandomAccess随机访问接口 ,Cloneable克隆接口, java.io.Serializable序列化接口;
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
    
}
  • 初始容量大小 
//初始容量为10
private static final int DEFAULT_CAPACITY = 10;
//空数组,在用户指定容量为 0 时返回
private static final Object[] EMPTY_ELEMENTDATA = {};
//空数组,默认返回
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

//对象数组,集合元素存放在该数组中。用于非私有以简化嵌套类访问
//ArrayList基于数组实现,用该数组保存数据,
//ArrayList 的容量就是该数组的长度
transient Object[] elementData; // non-private to simplify nested class access
//ArrayList实际存储的数据数量
private int size;
  • 构造方法
//构造具有指定初始容量的空列表。
public ArrayList(int initialCapacity) {
    if (initialCapacity > 0) {
        //直接new一个指定容量的对象数组
        this.elementData = new Object[initialCapacity];
    } else if (initialCapacity == 0) {
        //空对象数组
        this.elementData = EMPTY_ELEMENTDATA;
    } else {
        //如果initialCapacity < 0则抛出异常
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    }
}

//构造一个初始容量为10的空列表。
//当元素第一次被加入时,扩容至默认容量 10
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

//根据集合对象构造ArrayList集合
public ArrayList(Collection<? extends E> c) {
    //将集合对象转换为对象数组
    elementData = c.toArray();
    //把转化后的Object[]数组长度赋值给当前ArrayList的size,并判断是否为0
    if ((size = elementData.length) != 0) {
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        //判断是否是对象数组类型
        if (elementData.getClass() != Object[].class)
           //如果不是Object[]类型,则转换为Object[]类型
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    } else {
        // replace with empty array.
        this.elementData = EMPTY_ELEMENTDATA;
    }
}
  • 自动扩容
//自动扩容
public void ensureCapacity(int minCapacity) {
    //计算最小扩充的容量
    int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
        // 判断是不是空的ArrayList,如果是空则最小扩充容量为10,否则最小扩充量为0
        ? 0
        // 默认扩充容量为10
        : 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++;

    // 防止溢出代码:确保指定的最小容量 > 数组缓冲区当前的长度
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

//数组缓冲区最大存储容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

//增加容量(扩容),以确保它至少可以容纳由最小容量参数minCapacity指定的元素数量
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    //新容量 = 旧容量 + (旧容量 / 2)
    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
        //OutOfMemoryError内存溢出
        throw new OutOfMemoryError();
        //最大容量分配为:Integer.MAX_VALUE
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

二、常用API:

【a】size()、isEmpty()、contains()、indexOf()、lastIndexOf()

//返回ArrayList实际存储的元素数量
public int size() {
    return size;
}

//判断元素是否为空
public boolean isEmpty() {
    //实际上判断长度是否等于0
    return size == 0;
}

//判断是否包含某个元素
public boolean contains(Object o) {
    //根据indexOf()来实现,下标>=0表示存在,-1表示否则不存在
    return indexOf(o) >= 0;
}

//找出对应元素在集合中第一次出现的下标
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++)
        //正序循环遍历elementData对象数组,一个一个比较
            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--)
         //倒序循环遍历elementData对象数组,一个一个比较
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

【b】clone()、toArray()

//返回此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);
}

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

【c】elementData()

//根据下标,返回集合中某个元素
@SuppressWarnings("unchecked")
E elementData(int index) {
    return (E) elementData[index];
}

//根据下标,返回集合中某个元素
public E get(int index) {
    //首先检查下标是否越界
    rangeCheck(index);
    //根据下标返回数组对应下标的元素
    return elementData(index);
}

//检查给定的索引是否在范围内
private void rangeCheck(int index) {
    if (index >= size)
    //抛出IndexOutOfBoundsException数组越界异常
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

【d】set()

//将此列表中指定位置的元素替换为指定的元素
public E set(int index, E element) {
    //首先检查下标是否越界
    rangeCheck(index);
    //获取旧下标对应的值
    E oldValue = elementData(index);
    //更新数组中对应下标的值为element
    elementData[index] = element;
    //返回更新前的值
    return oldValue;
}

【e】add()

//将指定的元素追加到此列表的末尾
public boolean add(E e) {
    //扩容
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    //增加size,然后新增一个数组元素,下标为(size + 1)
    elementData[size++] = e;
    return true;
}

//扩容操作
private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }

    ensureExplicitCapacity(minCapacity);
}

//将指定元素插入其中的指定位置列表。
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长度加1
    size++;
}

private void rangeCheckForAdd(int index) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

我们通过简单的代码分析一下自动扩容的流程:

List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
list.add("8");
list.add("9");
list.add("10");
//添加到11这个元素的时候开始扩容
//minCapacity = 11 此时elementData.length=10 ,由于11>10达到扩容条件,进入grow()进行扩容
// 新容量 = 旧容量 + (旧容量 / 2) = 10 + (10 / 2) = 15
list.add("11");
System.out.println(list);
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

【f】remove()

//删除列表中指定位置的元素
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; // clear to let GC do its work
    //返回删除后的元素值
    return oldValue;
}

//从列表中删除指定元素的第一个匹配项,如果它存在。如果列表不包含该元素,则不变
public boolean remove(Object o) {
    if (o == null) {
        //循环判断数组元素,挨个判断是否为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);
     //将最后一个元素置空,方便GC垃圾回收                    
    elementData[--size] = null; // clear to let GC do its work
}

【g】clear()

//从列表中删除所有元素。将列表调用返回后为空。
//将数组缓冲区所以元素置为null
public void clear() {
    modCount++;

    // clear to let GC do its work
    for (int i = 0; i < size; i++)
    //将数组每个元素都置为null,方便GC垃圾回收
        elementData[i] = null;
    //更新长度为0
    size = 0;
}

【h】addAll()

//将指定集合中的所有元素追加到列表中
//ArrayList 是线程不安全的,如果同时有两个线程,一个线程向list中新增元素,一个线程修改list中元素,可能会存在线程安全问题
public boolean addAll(Collection<? extends E> c) {
    //将集合对象转换为对象数组
    Object[] a = c.toArray();
    //需要增加的元素的个数
    int numNew = a.length;
    //扩容,增量modCount
    ensureCapacityInternal(size + numNew);  // Increments modCount
    //数组拷贝,将需要添加的对象数组拷贝到elementData中
    System.arraycopy(a, 0, elementData, size, numNew);
   //更新size
    size += numNew;
    return numNew != 0;
}

//将指定集合中的所有元素插入列表,从指定位置开始。
//原本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);
    //拷贝下标从0至index下标的元素
    System.arraycopy(a, 0, elementData, index, numNew);
    //更新size
    size += numNew;
    return numNew != 0;
}

【i】removeRange()

//从该列表中删除其索引位于之间的所有元素,将后面的元素往前面移动
//需要将toIndex之后(包括toIndex)的元素都向前移动(toIndex-fromIndex)个位置
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++) {
        //将删除之后的元素置空,方便GC垃圾回收         
        elementData[i] = null;
    }
    size = newSize;
}

详细可以参考下图debug:System.arraycopy数组拷贝后:

【j】removeAll()

//元素中包含的所有元素从该列表中移除指定的集合。
public boolean removeAll(Collection<?> c) {
    //判断是否为null,如果为null抛出NullPointerException空指针异常
    Objects.requireNonNull(c);
    return batchRemove(c, false);
}

//从这个列表中删除所有不包含在指定集合中的元素。
public boolean retainAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, true);
}

//批量移除集合元素
//complement: 是否是补集
//complement: true:移除list中除了c集合中的所有元素;
//complement: false:移除list中c集合中的元素;
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;
}

【k】writeObject()、readObject()

//将ArrayList实例的状态保存到流中is,序列化它
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);

    // 以合适的顺序写入所有的元素
    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
        //就像clone(),根据大小而不是容量来分配数组
        ensureCapacityInternal(size);

        Object[] a = elementData;
        // Read in all elements in the proper order.
        //按适当的顺序读取所有的元素
        for (int i=0; i<size; i++) {
            a[i] = s.readObject();
        }
    }
}

【l】iterator()

//适当的顺序对列表中的元素返回一个迭代器。
public Iterator<E> iterator() {
    return new Itr();
}

//Itr是私有内部类
private class Itr implements Iterator<E> {
    //游标,下一个要返回的元素的索引
    int cursor;       // index of next element to return
   //最后一个返回元素的索引;-1如没有
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    //判断是否还有下一个元素
    public boolean hasNext() {
        //即判断游标是否到了list的最大长度
        return cursor != size;
    }

    //返回下一个元素
    @SuppressWarnings("unchecked")
    public E next() {
        checkForComodification();
        //i为游标,即当前元素的索引
        int i = cursor;
        if (i >= size)
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)
        //检查list中数量是否发生变化
            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;
            //将最后一个元素返回的索引重置为-1
            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() {
        //在迭代list集合时元素数量发生变化时会造成modCount和expectedModCount不相等
        //当expectedModCount和modCount不相等时,就抛出ConcurrentModificationException
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

【m】sort()

//排序,可以传入比较器接口实现自定义排序
@Override
@SuppressWarnings("unchecked")
public void sort(Comparator<? super E> c) {
    final int expectedModCount = modCount;
    //底层根据Arrays.sort()实现
    Arrays.sort((E[]) elementData, 0, size, c);
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    modCount++;
}

ArrayList底层实际上都是在操作对象数组来完成的,用的比较多的就是数组的拷贝System.arraycopy:

public static native void arraycopy(Object src,  int  srcPos,
                                    Object dest, int destPos,
                                    int length);
其中:src表示源数组,srcPos表示源数组要复制的起始位置,desc表示目标数组,length表示要复制的长度。

示例:

int[] sourceArr = {1, 2, 3};
int[] targetArr = {4, 5, 6};
System.arraycopy(sourceArr, 0, targetArr, 0, sourceArr.length);
for (int i : sourceArr) {
    System.out.print(i + " ");
}
System.out.println();
for (int j : targetArr) {
    System.out.print(j + " ");
}

发布了197 篇原创文章 · 获赞 86 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/Weixiaohuai/article/details/103838130