美文网首页
ArrayList源码解析

ArrayList源码解析

作者: 小小的coder | 来源:发表于2020-01-14 19:31 被阅读0次

下面就跟我一起撸起ArrayList的源码吧。

本文将从几个常用方法下手,来阅读ArrayList的源码。
按照从构造方法->常用API(增、删、改、查)的顺序来阅读源码,并会讲解阅读方法中涉及的一些变量的意义。了解ArrayList的特点、适用场景。

如果本文中有不正确的结论、说法,请大家提出和我讨论,共同进步,谢谢。

概要
概括的说,ArrayList 是一个动态数组,它是线程不安全的,允许元素为null。
其底层数据结构依然是数组,它实现了List<E>, RandomAccess, Cloneable, java.io.Serializable接口,其中RandomAccess代表了其拥有随机快速访问的能力,ArrayList可以以O(1)的时间复杂度去根据下标访问元素。

因其底层数据结构是数组,所以可想而知,它是占据一块连续的内存空间(容量就是数组的length),所以它也有数组的缺点,空间效率不高。

由于数组的内存连续,可以根据下标以O1的时间读写(改查)元素,因此时间效率很高。

当集合中的元素超出这个容量,便会进行扩容操作。扩容操作也是ArrayList 的一个性能消耗比较大的地方,所以若我们可以提前预知数据的规模,应该通过public ArrayList(int initialCapacity) {}构造方法,指定集合的大小,去构建ArrayList实例,以减少扩容次数,提高效率。

或者在需要扩容的时候,手动调用public void ensureCapacity(int minCapacity) {}方法扩容。
不过该方法是ArrayList的API,不是List接口里的,所以使用时需要强转:
((ArrayList)list).ensureCapacity(30);

当每次修改结构时,增加导致扩容,或者删,都会修改modCount。

构造方法

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

//默认构造函数里的空数组
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

//存储集合元素的底层实现:真正存放元素的数组
transient Object[] elementData; // non-private to simplify nested class access

//当前集合中元素数量
private int size;

//|||构造方法

//默认构造方法
public ArrayListCode() {
    //默认构造函数只是将空数组赋值给了elementData
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

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

//带初始容量的构造方法
public ArrayListCode(int initialCapacity) {
    //如果初始容量大于0,则新建一个长度为initialCapacity
    // 的Object数组
    //注意这里并没有修改size(对比第三个构造)
    if (initialCapacity > 0) {
        this.elementData = new Object[initialCapacity];
    }
    //如果容量为0,直接将EMPTY_ELEMENTDATA空数组赋值给elementData
    else if (initialCapacity == 0) {
        this.elementData = EMPTY_ELEMENTDATA;
    }
    //容量小于0,直接抛异常
    else {
        throw new IllegalArgumentException("Illegal Capacity: " +
                initialCapacity);
    }
}

//利用别的集合类来构建ArrayList的构造函数
public ArrayListCode(Collection<? extends E> c) {
    //直接利用Collection.toArray()得到一个对象数组 ,并赋值给elementData
    elementData = c.toArray();
    //因为size代表的是集合中元素的数量,所以通过别的集合来构造ArrayList时
    // ,需要修改size给size赋值
    if ((size = elementData.length) != 0) {
        //这里是当c.toArray()转换出错,没有返回Object[]时
        // ,利用Arrays.copyOf来复制集合c中的元素到elementData中???
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    } else {
        //如果集合c中元素数量为0,则将空数组EMPTY_ELEMENTDATA赋值给elementData
        this.elementData = EMPTY_ELEMENTDATA;
    }
}

小结一下,构造函数走完之后,会构建出数组elementData和数量size。

这里大家要注意一下Collection.toArray()这个方法,在Collection子类各大集合的源码中,高频使用了这个方法去获得某Collection的所有元素。

关于方法:Arrays.copyOf(elementData, size, Object[].class),就是根据class的类型来决定是new 还是反射去构造一个泛型数组,同时利用native函数,批量赋值元素至新数组中。
数组,同时利用native函数,批量赋值元素至新数组中。
如下:
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
//根据class的类型来决定是new 还是反射去构造一个泛型数组
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
//利用native函数,批量赋值元素至新数组中
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}

值得注意的是,System.arraycopy也是一个很高频的函数,大家要留意一下。
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);

常用API

1 增

每次 add之前,都会判断add后的容量,是否需要扩容。

public boolean add(E e) {
//每次add之前,都会判断add后的容量,是否需要扩容
ensureCapacityInternal(size + 1);
//在数组末尾追加一个元素,并修改size
elementData[size++] = e;
return true;
}

private void ensureCapacityInternal(int minCapacity) {
    //利用==可以判断数组是否使用的默认构造函数进行的初始化
    //即---常用的不传参的构造函数
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }

    ensureExplicitCapacity(minCapacity);
}

private void ensureExplicitCapacity(int minCapacity) {
    //如果确定要扩容,会修改modCount
    modCount++;

    // overflow-conscious code
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

//整型最大值-8 此处用于防止大于int最大值
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

//需要扩容的话,默认扩容一半
private void grow(int minCapacity) {
    int oldCapacity = elementData.length;
    //默认扩容一半
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    //如果还不够,那么就用能容纳的最小容量(add后的容量)
    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) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
}

//
public void add(int index, E element) {
    //越界判断 如果越界则抛出异常
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

    //每次add之前,都会判断add后的容量,是否需要扩容
    ensureCapacityInternal(size + 1);
    //将index开始的数据 向后移动一位 !!!注:关键操作
    System.arraycopy(elementData, index, elementData, index + 1,
            size - index);
    //插入当前元素element到index位置
    elementData[index] = element;
    size++;//当前集合中元素数量+1
}

//
public boolean addAll(Collection<? extends E> c) {
    Object[] a = c.toArray();
    int numNew = a.length;
    //每次add之前,都会判断add后的容量,是否需要扩容
    ensureCapacityInternal(size + numNew);
    //把数组a中元素 复制至elementData中
    System.arraycopy(a, 0, elementData, size, numNew);
    size += numNew;//当前集合中元素数量+numNew
    return numNew != 0;//有元素被复制 则返回true
}

//
public boolean addAll(int index, Collection<? extends E> c) {
    //越界判断 如果越界则抛出异常
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

    Object[] a = c.toArray();
    int numNew = a.length;
    //每次add之前,都会判断add后的容量,是否需要扩容
    ensureCapacityInternal(size + numNew);  // Increments modCount

    int numMoved = size - index;
    if (numMoved > 0)
        //将index开始的数据 向后移动numNew位 !!!注:关键操作
        System.arraycopy(elementData, index, elementData, index + numNew,
                numMoved);
    //把elementData中从index到numNew的元素 用a一一赋值
    System.arraycopy(a, 0, elementData, index, numNew);
    size += numNew;//当前集合中元素数量+numNew
    return numNew != 0;//有元素被复制 则返回true
}

总结:
add、addAll。
先判断是否越界,是否需要扩容。
如果扩容, 就复制数组。
然后设置对应下标元素值。

值得注意的是:
1 如果需要扩容的话,默认扩容一半。如果扩容一半不够,就用目标的size作为扩容后的容量。
2 在扩容成功后,会修改modCount

2 删
public E remove(int index) {
//判断是否越界
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
//修改modCount,因为结构改变了
modCount++;
//读出要删除的值
E oldValue = (E) elementData[index];//根据下标从数组取值 并强转

    int numMoved = size - index - 1;
    if (numMoved > 0)
        //利用赋值System.arraycopy覆盖index位置的元素---用index + 1
        System.arraycopy(elementData, index + 1, elementData, index,
                numMoved);
    //置空原尾部数据(即size-1位置的元素) 不在强引用,等待被gc处理
    elementData[--size] = null;
    return oldValue;//返回被删除的index位置的value值
}

//删除该元素在数组中第一次出现的位置上的数据。
// 如果有该元素则删除后返回true,否则返回false
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);//根据index删除元素
                return true;
            }
    }
    return false;
}

//和remove(int index)类似  但fastRemove专为remove(Object o)调用
//不用判断越界和取出元素   但是modCount也需要被修改
private void fastRemove(int index) {
    modCount++; //修改modCount,因为结构改变了
    int numMoved = size - index - 1;//
    if (numMoved > 0)
        //利用赋值System.arraycopy覆盖index位置的元素---用index + 1
        System.arraycopy(elementData, index + 1, elementData, index,
                numMoved);
    //置空原尾部数据(即size-1位置的元素) 不在强引用,等待被gc处理
    elementData[--size] = null;
}

//批量删除elementDatah中 含有c中元素的值
public boolean removeAll(Collection<?> c) {
    //判断当前c是否为空 为空---throw空指针异常
    Objects.requireNonNull(c);
    return batchRemove(c, false);
}

//保留elementDatah中 含有c中元素的值
public boolean retainAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, true);
}

//批量删除或保留---下文对complement==false进行讲解 true类似
private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    //w代表批量删除后 数组还剩多少元素
    int r = 0, w = 0;
    boolean modified = false;
    try {
        //高效的保存 2个集合中共有元素的算法
        for (; r < size; r++)
            if (c.contains(elementData[r]) == complement)
                elementData[w++] = elementData[r];
    } finally {
        //出现异常会导致r != size,则将出现异常位置(r)处后面的数据
        //全部复制覆盖到elementData数组中。
        if (r != size) {
            System.arraycopy(elementData, r,
                    elementData, w,
                    size - r);
            //复制后修改w的数量
            w += size - r;
        }
        //置空数组elementData中 w后面的所有元素
        if (w != size) {
            //循环进行置空w后所有元素,等待gc进行处理
            for (int i = w; i < size; i++)
                elementData[i] = null;
            //修改modCount size - w次
            modCount += size - w;
            size = w;//修改size为w
            modified = true;//为true表示修改成功
        }
    }
    return modified;
}

//删除指定范围内 所有元素
protected void removeRange(int fromIndex, int toIndex) {
    //toIndex大于fromIndex检查
    if (toIndex < fromIndex) {
        throw new IndexOutOfBoundsException("toIndex < fromIndex");
    }

    //修改modCount
    modCount++;
    int numMoved = size - toIndex;
    //复制数组 fromIndex到toIndex的元素被覆盖赋值
    System.arraycopy(elementData, toIndex, elementData, fromIndex,
            numMoved);

    //清空 newSize=size-移除去除元素个数===剩余元素个数
    //置空newSize后面的元素 等待gc进行处理
    int newSize = size - (toIndex - fromIndex);
    for (int i = newSize; i < size; i++) {
        elementData[i] = null;
    }
    //修改size为newSize
    size = newSize;
}

从这里我们也可以看出,当用来作为删除元素的集合里的元素多余被删除集合时,也没事,只会删除它们共同拥有的元素。

小结:
1 删除操作一定会修改modCount,且可能涉及到数组的复制,相对低效。
2 批量删除中,涉及高效的保存两个集合公有元素的算法,可以留意一下。

3 改
不会修改modCount,相对增删是高效的操作。
public E set(int index, E element) {
//越界检测
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
//取出index处的旧元素
E oldValue = (E) elementData[index];
//覆盖index位置元素为 element
elementData[index] = element;
//操作成功 返回index处的旧元素
return oldValue;
}
4 查
不会修改modCount,相对增删是高效的操作。
public E get(int index) {
//越界检测
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

    //从elementData数组中 取出index处元素
    return (E) elementData[index];
}

5 清空,clear
会修改modCount。
public void clear() {
modCount++;//修改modCount

    //将所有元素置空 等待gc进行处理
    for (int i = 0; i < size; i++)
        elementData[i] = null;
    //当前集合中元素数量同步置为0
    size = 0;
}

6 包含 contains
//查找数组elementData中是否含有值为o的第一个值
//注:batchRemove中的contains的具体实现 调用的就是这个???
public boolean contains(Object o) {
return indexOf(o) >= 0;
}

//普通的for循环寻找值 只不过会根据目标对象是否为null分别循环查找
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;
}

//查找数组elementData中是否含有值为o的最后一个值的index
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;
}

7 判空 isEmpty()
//isEmpty() 当前元素个数为0
public boolean isEmpty() {
return size == 0;
}
8 迭代器 Iterator.
//
public Iterator<E> iterator() {
return new Itr();
}

//
private class Itr implements Iterator<E> {
    protected int limit = ArrayListCode.this.size;

    //默认是0
    int cursor;       // 下一个返回元素的下标index
    int lastRet = -1; // 上一次返回元素的index标志位; 为-1表示没有
    int expectedModCount = modCount;//用于判断集合是否被修改过结构的 标志

    //用于判断游标是否移动至尾部
    public boolean hasNext() {
        return cursor < limit;
    }

    @SuppressWarnings("unchecked")
    public E next() {
        //判断是否有修改过List的结构,如果有修改则抛出异常
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        int i = cursor;
        if (i >= limit)//判断是否越界
            throw new NoSuchElementException();
        Object[] elementData = ArrayListCode.this.elementData;
        //再次判断是否越界
        // 当我们在这里操作时 可能有异步线程修改了当前List集合
        if (i >= elementData.length)
            throw new ConcurrentModificationException();
        cursor = i + 1;//游标+1 用于获取下个元素
        //返回元素 并设置上一次返回元素lastRet的下标
        return (E) elementData[lastRet = i];
    }

    //remove掉 上一次next的元素
    public void remove() {
        //先判断是否next过
        if (lastRet < 0)
            throw new IllegalStateException();
        //判断是否有修改过List的结构,如果有修改则抛出异常
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();

        try {
            //删除元素 remove方法内会修改modCount
            //所以后面要更新Iterator中的lastRet这个标志位
            ArrayListCode.this.remove(lastRet);
            cursor = lastRet;//要删除的游标
            lastRet = -1;//不能重复删除 所有修改删除的标志位
            expectedModCount = modCount;//更新 判断集合是否有修改的标志位
            limit--;//list集合元素个数-1
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

}

总结
增删改查中, 增导致扩容,则会修改modCount,删一定会修改。 改和查一定不会修改modCount。
扩容操作会导致数组复制,批量删除会导致 找出两个集合的交集,以及数组复制操作,因此,增、删都相对低效。 而 改、查都是很高效的操作。
因此,结合特点,在使用中,以Android中最常用的展示列表为例,列表滑动时需要展示每一个Item(element)的数组,所以 查 操作是最高频的。相对来说,增操作 只有在列表加载更多时才会用到 ,而且是在列表尾部插入,所以也不需要移动数据的操作。而删操作则更低频。 故选用ArrayList作为保存数据的结构。
在面试中还有可能会问到和Vector的区别,我大致看了一下Vector的源码,内部也是数组做的,区别在于Vector在API上都加了synchronized所以它是线程安全的,以及Vector扩容时,是翻倍size,而ArrayList是扩容50%。
————————————————
原文链接:https://blog.csdn.net/zxt0601/article/details/77281231

相关文章

网友评论

      本文标题:ArrayList源码解析

      本文链接:https://www.haomeiwen.com/subject/qpwaactx.html