ArrayList源码分析

目录

重要属性分析

属性说明

关于属性的一点思考

重要方法分析

构造方法

add 

addAll

remove

removeAll

ensureCapacityInternal

trimToSize


简介:ArrayList 是不同步的基于数组可调整大小的队列。实现所有可选的列表操作,并允许所有元素,包括 null。除了实现List接口之外,该类还提供了操作内部用于存储列表的数组大小的方法。

重要属性分析

属性说明

    transient Object[] elementData; // non-private to simplify nested class access

    private int size;

    protected transient int modCount = 0;

elementData:arrayList数据存储

size:elementData数组中实际有效内容数量

modCount:实际操作的次数,包括add、remove等操作

关于属性的一点思考

size直接通过elementData数组长度表示不可以么?

实际通过阅读自动扩容会明白elementData为了更高效的存储数据,会生成一个长度大于实际item的数组,所以elementData的长度无法准确表达数量。

modCount的作用是什么?

因为arrayList是不保证线程安全,modCount主要应用于迭代器遍历的时候进行判断是否被修改

        int expectedModCount = modCount;
        public E next() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            ......
        }

从代码上看modCount赋值给expectedModCount,这是在创建迭代器的过程中进行的操作,在遍历的过程中,每次next都是判断arrayList的modCount和expectModCount是否相等,如果不相等就说明已经被修改。

重要方法分析

构造方法

    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

从构造方法中可以看到,这里主要是给elementData进行赋值,其中DEFAULTCAPACITY_EMPTY_ELEMENTDATA是一个空数组。

private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

 构造函数还有两个带参构造和这个原理基本相同,都是给elementData进行赋值。

add 

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

add方法的逻辑比较简单,调用了ensureCapacityInternal自动扩容逻辑,把需要添加的元素放到数组中。

    public void add(int index, E element) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

这个add方法多了一个index参数,是要指定插入的下标,从代码上和不带index的add方法相比,这里在完成自动扩容之后多了一个arraycopy的方法,就是把原来[index,size]的数组复制到[index+1,size+1]的位置,空出来index的位置给将要插入的element。

自动扩容的逻辑这里先不展开,我们放到后面进行分析。

addAll

    public boolean addAll(Collection<? extends E> c) {    
        boolean modified = false;
        for (E e : c)
            if (add(e))
                modified = true;
        return modified;
    }

这里主要是遍历Collection然后调用add方法添加。

remove

    public E remove(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

        modCount++;
        E oldValue = (E) elementData[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

        return oldValue;
    }

在remove指定index的方法中,需要从elementData数组中拿出指定下标的元素,然后在通过arrayCopy把原来[index+1,size]的数组复制到[index,size-1],同时把elementData下标为size内容置为空,size自减。

    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
    }

在remove Object方法中是需要先遍历查找到index,然后在通过fastMove方法根据index进行remove操作,这里的fastMove和remove index 方法有点相似,但是更加轻量级。

removeAll

    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

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

遍历elementData数组,过滤出不属于Collection的item,重新放入elentaData数组。如果w!=size说明过滤后elementData的有效内容发生变化,需要把无效内容再次置空。这段代码有效绕,可能单步跟踪一下会比较好理解。

ensureCapacityInternal

    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

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

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        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);
    }

自动扩容这里主要是在add方法中使用,ensureCapacityInternal 中的 minCapacity 参数是size+1,这是为了保证数组elementData不会越界,因为size是当前数组中有效数据长度,而size+1就是add之后的数组中有效数据长度。

在ensureExplicitCapacity方法中判断如果minCapacity 大于elementData就说明数组需要调用grow方法进行扩容。

grow方法扩容是把当前elementData长度扩1.5倍

        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);

这里对newCapacity也会进行检查,包括是否超过 MAX_ARRAY_SIZE 或者小于minCapacity

确定了newCapacity之后,调用Arrays.copyOf(elementData, newCapacity) 新建一个newCapacity长度的数组,并把原来数组中的内容进行拷贝

    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

产生的新数组赋值给elementData就完成了自动扩容。

trimToSize

    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

trimToSize这里主要是根据size来调整一下elementData实际大小,因为默认数组长度是10,并且每次扩容大多是扩容1.5倍,所以在确定list内容后,可以调用trimToSize 来缩小一下elementData长度,减少空间占用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值