ArrayList 源码学习

一、概念:

ArrayList ,基于 [] 数组实现的,支持自动扩容的动态数组。相比数组来说,因为其支持自动扩容的特性,成为我们日常开发中,最常用的集合类,没有之一。

二、实现类:

ArrayList 实现了 List<E>, RandomAccess, Cloneable, java.io.Serializable 接口,

List<E> 接口,提供数组的添加,删除,修改,迭代遍历等操作。

RandomAccess:表示接口可以随机访问,即可以通过get(i),获取元素,时间复杂度为O(1)。

java.io.Serializable:序列化标记接口,表示它可以序列化。

Cloneable:标记接口,支持克隆。

三、属性:

elementData:属性:元素数组。

size:数组大小,表示已使用的数组大小。

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     * 已使用的数组大小
     * @serial
     */
    private int size;

    /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};//这个指定了 构造参数为0

    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //这个没有指定参数,无参构造创建的,空数组

四、构造函数:

有参构造:

    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    public ArrayList(int initialCapacity) {//尽量使用有参构造并且指定合适大小,避免数组扩容,影响性能.
        //带参构造方法,传递一个初始大小,
        if (initialCapacity > 0) {
            //创建一个指定大小的数组,
            this.elementData = new Object[initialCapacity]; // 创建指定大小的ArrayList
        } else if (initialCapacity == 0) {//初始如果指定的大小为0
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
           // 如果集合元素不是 Object[] 类型,则会创建新的 Object[] 数组,并将 elementData 赋值到其中,最后赋值给 elementData
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            //数组大小等于 0
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

无参构造:


    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        //默认构造方法,创建了一个空的数组
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

在使用数组的时候尽量分配好合适的大小空间,避免频繁扩容,影响效率。

五、添加单个元素:

    public boolean add(E e) {//添加元素 最好的复杂度O(1)
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { //如果没有指定初始大小,第一次调用add方法的时候,会在这里扩容 默认的大小就是10
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);//如果指定的初始大小为0 ,那么第一次扩容的时候minCapacity 为1, 第二次添加元素扩容为2,
    }

    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; // 目前数组大小
        // 新容量为oldCapacity加上oldCapacity除以2(即>>右移位运算),这个是自动扩展数组大小的算法  每次扩容都是原来容量的1.5倍
        // 当newCapacity大于minCapacity时并且没有到达数组最大值,都会将数组扩展为newCapacity大小
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity; // 如果newCapacity小于指定的minCapacity,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 溢出
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ? // minCapacity大于数组规定的最大大小,则取Integer最大值,否则去数组规定的最大大小
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

ArrayList支持主动扩容,还支持手动缩容。

    public void trimToSize() {//缩容,创建大小恰好够用的新数组,并将原数组复制到其中. 支持手动缩容
        modCount++;//增加修改次数
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

七、添加多个元素:

    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;  //数组的长度,
        ensureCapacityInternal(size + numNew);  // Increments modCount 保证elementData数组的长度够用.
        System.arraycopy(a, 0, elementData, size, numNew);  //将集合c 的内容拷贝到elementData中 ,从索引size往后开始复制,长度为numNew
        size += numNew;
        return numNew != 0;
    }

    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个元素         
     ) 向后移动移动到size后面
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);
        //将c集合中的元素添加到 elementData 中.
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
     }

八、移除元素:

    public E remove(int index) {    //移除某个索引上的元素,
        rangeCheck(index);

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

        int numMoved = size - index - 1;//计算index 后面需要需要移动的元素个数 , (0-1-2-3-4-5-6)    [7-3-1=3]
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved); // 将从index+1开始的元素向前移动一个位置
        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); // 私有remove,去掉了界限检查且没有返回值
                    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 把队尾元素置空
    }

九、清空元素:

    public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)//正序遍历数组,正序设置null
            elementData[i] = null;

        size = 0;
    }

十、查找某个元素:

    public E get(int index) {
        rangeCheck(index); // 越界检查

        return elementData(index);
    }

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


    public int indexOf(Object o) {//查找某个指定元素,
        if (o == null) {
            for (int i = 0; i < size; i++)//遍历数组.
                if (elementData[i]==null)//比较元素是否为null
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))//比较元素是否为o
                    return i;  //找到,返回索引值
        }
        return -1;  //找不到,返回-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--)//倒序遍历
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;//找不到就返回-1
    }

十一、设置特定位置上的元素:

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

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

十二、创建子数组:

   // subList方法虽然返回的是list的子列表,但其实是对list中一部分元素的操作,当向subList中插入或删除元素,list也会相应改变
    public List<E> subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size); // 验证参数范围
        return new SubList(this, 0, fromIndex, toIndex);
    }

private class SubList extends AbstractList<E> implements RandomAccess {
        private final AbstractList<E> parent;   //和根节点Root 共享一个List,
        private final int parentOffset;     // 父节点的偏移量
        private final int offset;   //字节点起始位置
        int size;                  //

        SubList(AbstractList<E> parent,
                int offset, int fromIndex, int toIndex) {
            this.parent = parent;
            this.parentOffset = fromIndex;
            this.offset = offset + fromIndex;
            this.size = toIndex - fromIndex;    //这个size 限制了 子集合的大小
            this.modCount = ArrayList.this.modCount;
        }

        public E set(int index, E e) {
            rangeCheck(index);
            checkForComodification();
            E oldValue = ArrayList.this.elementData(offset + index);
            ArrayList.this.elementData[offset + index] = e;
            return oldValue;
        }

        .......

}

实际上还是原来的数组,只不过限制了范围。

十三、迭代器:

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

    //为什么有for循环了 ?, 还需要迭代器或者foreach , 迭代器或者foreach 代码更简洁,不需要指定条件,循环变量, for循环需要指定循环变量,
    // 循环条件需要手动控制循环变量
    /**
     * An optimized version of AbstractList.Itr
     */
    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  //上一次访问元素的位置 初始为-1  表示无上一个访问的元素,
        int expectedModCount = modCount;    //数组的修改次数, 在迭代过程中,如果数组发生了变化,会抛出 ConcurrentModificationException 异常。

        public boolean hasNext() {
            return cursor != size;//如果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];
        }

        .......
}

总结:

  • ArrayList 是基于 [] 数组实现的 List 实现类,支持在数组容量不够时,一般按照 1.5 倍自动扩容。同时,它支持手动扩容、手动缩容。
  • ArrayList 随机访问时间复杂度是 O(1) ,查找指定元素的平均时间复杂度是 O(n) 。

  • ArrayList 移除指定位置的元素的最好时间复杂度是 O(1) ,最坏时间复杂度是 O(n) ,平均时间复杂度是 O(n) 。最好是在末尾(不需要移动元素)。

  • ArrayList 移除指定元素的时间复杂度是 O(n) 。需要遍历,然后移动元素。

  • ArrayList 添加元素的最好时间复杂度是 O(1) ,最坏时间复杂度是 O(n) ,平均时间复杂度是 O(n) 。

  • Redis 的String 数据结构和Java ArrayList 有点类似。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值