ArrayList源码解析

记录一下自己看的源码,就当复习了

引用

Java集合 ArrayList源码分析

成员变量

    //默认容量
    private static final int DEFAULT_CAPACITY = 10;
    //空数组,用于无参构造函数
    private static final Object[] EMPTY_ELEMENTDATA = {};
    //默认空数组,用于有参构造函数
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    //实际存储元素的数组
    transient Object[] elementData;
    //集合元素数量
    private int size;
    //集合最大容量
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    //父类变量,表示List容量修改次数
    protected transient int modCount = 0;

构造函数

1.无参构造函数

    public ArrayList() {
        //无参构造函数,elementData 指向DEFAULTCAPACITY_EMPTY_ELEMENTDATA 空数组
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

2.有参构造函数

    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            //初始化为一个容量为initialCapacity的数组
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            //elementData 指向EMPTY_ELEMENTDATA空数组
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

3.参数为集合的构造函数

    public ArrayList(Collection<? extends E> c) {
        //参数集合转为Array赋给存储元素的数组
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] 
            if (elementData.getClass() != Object[].class)
                //元素为空时,复制数组,copyOf方法中有类型检查
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // 若参数集合为空,则返回空数组EMPTY_ELEMENTDATA.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

添加

1.添加单个元素

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            //用无参构造函数,添加单个元素,大小为默认容量10
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        //容量变化次数增加1
        modCount++;
        //判断需要的实际元素容量是否大于数组容量,是则扩容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    private void grow(int minCapacity) {
        int oldCapacity = elementData.length;
        //容量增加为1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
        //newCapacity 可能为0,此时采用传入的minCapacity作为扩容后的容量
            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();
        //容量不能超过Integer.MAX_VALUE
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

扩容机制如下:
1、先默认将列表大小newCapacity增加原来一半,即如果原来是10,则新的大小为15;
2、如果新的大小newCapacity依旧不能满足add进来的元素总个数minCapacity,则将列表大小改为和minCapacity一样大;即如果扩大一半后newCapacity为15,但add进来的总元素个数minCapacity为20,则15明显不能存储20个元素,那么此时就将newCapacity大小扩大到20,刚刚好存储20个元素;
3、如果扩容后的列表大小大于2147483639,也就是说大于Integer.MAX_VALUE - 8,此时就要做额外处理了,因为实际总元素大小有可能比Integer.MAX_VALUE还要大,当实际总元素大小minCapacity的值大于Integer.MAX_VALUE,即大于2147483647时,此时minCapacity的值将变为负数,因为int是有符号的,当超过最大值时就变为负数

    public static <T> T[] copyOf(T[] original, int newLength) {
        return (T[]) copyOf(original, newLength, original.getClass());
    }
    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;
    }
    //参数为原array,原起始位置,目标array,目标起始位置,需要复制的数组长度
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

2.指定位置添加元素

    public void add(int index, E element) {
        //位置检查
        rangeCheckForAdd(index);
        //扩容
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //复制数组,将原index及其以后的元素复制到index+1
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        //index位置赋值为添加的元素
        elementData[index] = element;
        size++;
    }

3.添加集合中的元素

    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        //扩容
        ensureCapacityInternal(size + numNew);  // Increments modCount
        //将集合中的元素复制到扩容后的数组后
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

4.指定位置添加集合中的元素

    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)
            //将原index到index+numMoved-1的元素复制到index+numNew及以后
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
        //将集合元素复制到index到index+numNew-1
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }

删除

1.删除指定位置元素

    public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            //将index+1及以后的元素复制到Index,相当于全部往前挪一位
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //最后一个元素设置为null
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

2.删除元素

    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
    }

3.删除指定范围的元素

    protected void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        //将toIndex之后的元素挪动到fromIndex
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex);
        //数组末尾元素全部置null
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }

4.删除集合中的所有元素

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

5.保留集合中的元素,删除其他元素(取交集)

    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }
    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++)
                //根据complete条件判断是否删除该元素
                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;
    }

获取集合对象

    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }
    E elementData(int index) {
        return (E) elementData[index];
    }

其他方法

1.指定位置设值

    public E set(int index, E element) {
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

2.判断元素是否存在

    public boolean contains(Object o) {
        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++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

序列化机制

1.writeObject

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

        // Write out all elements in the proper order.
        for (int i=0; i<size; i++) {
            s.writeObject(elementData[i]);
        }

        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

从上面的代码中我们可以看出ArrayList其实是有对elementData进行序列化的,只不过这样做的原因是因为elementData中可能会有很多的null元素,为了不把null元素也序列化出去,所以自定义了writeObject和readObject方法。
2.readObject

    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
            ensureCapacityInternal(size);

            Object[] a = elementData;
            // Read in all elements in the proper order.
            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }

迭代器

    public Iterator<E> iterator() {
        return new Itr();
    }

新建了一个叫Itr的对象,Itr类其实是ArrayList的一个内部类

    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

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

        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();
            }
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容