源码分析-1、ArrayList(jdk1.8)

ArrayList

因为最近开始准备面试,故想从源码角度开始扎实自己的java基础。ArrayList作为最常用的集合类之一,它的源码相比之下要简单的多,对于刚开始尝试阅读源码的人来说,它是比较好的入门。废话不多说,让我们开始对ArrayList进行剖析吧!(基于jdk1.8)

一、总览

在这里插入图片描述
如上图所示,图中共涉及6个接口(interface)以及2个抽象类(abstract class),我们来一一看下。

1、RandomAccess, Cloneable,Serializable

RandomAccess是个空接口,并没有什么实际方法,实现这个接口表示ArrayList支持快速随机访问,这跟ArrayList的底层实现有关系,ArrayList的底层数据结构是用数组来存储数据的,而数组天生具有根据索引直接获得元素的特性,故ArrayList的查询较快,时间复杂度为O(1),但是删除和增加元素较慢,时间复杂度为O(n),后面会根据源码一一讲解,这里点到为止;
Cloneable也是一个空接口,实现这个接口表示ArrayList可以被clone;
Serializable是一个序列化的接口,有兴趣的读者可以去研究下;Cloneable和Serializable并不在本文的研究范围内。

2、List

List是一个有序集合,因为有序,所以元素可以重复,它继承了Collection接口,而Collection接口又继承Iterable接口,Iterable接口允许对象可以被迭代器遍历。

public interface Iterable<T> {
    /**
     * 返回类型为T的元素上的迭代器
     *
     * @return an Iterator.
     */
    Iterator<T> iterator();
}

List接口定义了作为有序集合的大量基础方法,如下图
在这里插入图片描述
从这张图中可以看出,大多数方法都是从Collection接口继承而来,而Collection是java集合最基础的父接口,List在此接口的基础上扩展了自己作为有序集合特性的独有方法。
回到ArrayList,它除了实现List,RandomAccess, Cloneable,Serializable四个接口外,还继承了AbstractList这个抽象类,让我们来看看这个类的结构。
在这里插入图片描述
从这个图可以看出,AbstractList除了继承AbstractCollection,自己又实现了List接口。至此,ArrayList的总体结构一目了然,下来我们从源码开始分析。

二、成员变量

    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * Default initial capacity. 
     * 默认初始容量
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     * 用于空实例的共享空数组实例
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 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.
     * 共享的空数组实例用于默认大小的空实例。我们将其与 
     * EMPTY_ELEMENTDATA区别开来,以了解添加第一个元素时需要扩容多少    
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 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.
     * 用于存储ArrayList元素的数组缓冲区
     * ArrayList的容量是此数组缓冲区的长度。添加第一个元素时,
     * 任何具有  *elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA的空ArrayList都将扩展为DEFAULT_CAPACITY
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     *ArrayList的大小(它包含的元素数)
     * @serial
     */
    private int size;

根据源码,我们可以看出ArrayList有三个final静态成员变量,DEFAULT_CAPACITY(默认初始化容量)、EMPTY_ELEMENTDATA、DEFAULTCAPACITY_EMPTY_ELEMENTDATA。两个成员变量,elementData和size,而elementData这个Object类型的数组则是整个ArrayList的灵魂,是ArrayList的底层数据结构,所有add进ArrayList里面的元素都被elementData所维护。所以ArrayList的大多数方法都是对这个数组进行元素删除增加移位的操作,这里我们注意到这个数组是Object类型的,而java一切皆对象,这也解释了为什么ArrayList不能存放基础数据类型,只能存放相应的包装类型。
了解了ArrayList的成员变量,接下来就是重中之重,对ArrayList成员方法的分析。

三、成员方法

在阅读成员方法 之前,我们来看看ArrayList的构造方法。

1、构造函数
    /**
     * 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];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * 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)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

ArrayList有三个构造函数,分别为无参,接受一个int类型的值,接受一个Collection集合。这里较为复杂的就是接受一个Collection的构造函数,里面涉及到一个数组的拷贝Arrays.copyOf(elementData, size, Object[].class),ArrayList 无参构造器初始化时,默认大小是空数组,并不是大家常说的 10,10 是在第一次 add 的时候扩容的数组值。

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

这里面又调用到一个native方法System.arraycopy,这个方法因为涉及到数组的拷贝,十分耗性能。

    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

这个native方法在ArrayList中被大量使用,所以要知道这个方法的使用事项,因为是一个native方法,我们暂无需知道它的内部实现,只需掌握它的使用。
从参数名称我们就可以得知,这个是将一个源数组src从srcPos位置开始将后面的元素拷贝到目标数组dest的destPos位置,这里需要注意两个数组拷贝时的长度length,以免越界。
说完了构造函数,让我们从add函数开始,有进才有出。

2、add方法
    /**
     * Appends the specified element to the end of this list.
     * 将指定的元素追加到此列表的末尾
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

根据源码可以看出,add方法内调用了 ensureCapacityInternal(size + 1),让我们看看这个方法的实现。

    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        //如果实例化list时是调用的默认无参构造方法,则取minCapacity和
        //DEFAULT_CAPACITY两者的最大值为所需的最小容量
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }

    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
         //如果现在的elementData长度无法满足所需的最小容量则要进行扩容
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    /**
     * Increases the capacity to ensure that it can hold at least the 
     * number of elements specified by the minimum capacity argument.
     * 增加容量,以确保它至少可以容纳最小容量参数指定的元素个数
     * @param minCapacity the desired minimum capacity 所需的最小容量
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        //扩容为原来数组的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //如果计算出的新数组容量仍无法满足所需最小容量minCapacity,则直接使用minCapacity作为扩容后的新数组长度
        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
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

add方法内最重要的就是grow方法,实现其实很简单,就是之前提起的那个数组拷贝方法,当所需最小容量大于现数组长度时,则要进行扩容,扩容长度为原来数据长度的1.5倍。
同时add还有一个重载方法,如下

    public void add(int index, E element) {
        rangeCheckForAdd(index);
        //检查是否需要扩容
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //将数组从index位置处(包括index)后的所有元素向后移一位,空出index位置(其实没有空出,还是存在元素)
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        //更新index处的元素值
        elementData[index] = element;
        size++;
    }

这个重载方法相对于之前的add方法,多了一步数组复制拷贝。

2、remove方法

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

        modCount++;
        E oldValue = elementData(index);
        //计算是否需要复制拷贝数组,当且仅当 index为size-1即删除最后一个元素时,才不需要移动原数组
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //size-1位置的元素置为空,即最后一个元素
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }
    
    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 remove method that skips bounds checking and does not
     * return the value removed.
     */
    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方法也有两个重载函数,一个是根据索引index,一个是根据元素,可以看出根据元素删除的方法最终也是先定位所删除元素的索引再调用fastRemove(int index)根据索引删除。

3、get,set,toArray方法
    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;
    }
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }
    public E get(int index) {
        rangeCheck(index);

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

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

这四个方法都比较简单,都是数组的基本操作。
至此,ArrayList的常用方法都分析了,不常用的方法,如果读者感兴趣可以试着自己去分析,但是大体操作都是类似的,都是对数组的各种操作,要注意数组复制拷贝时边界值索引的限制,以及复制元素个数的计算。

四、迭代器模式

    private class Itr implements Iterator<E> {
        //记录下一个要返回元素的索引index
        int cursor;       // index of next element to return
        //记录前一个next方法返回的索引index
        int lastRet = -1; // index of last element returned; -1 if no such
        //记录在迭代过程中 list结构有没有被修改
        int expectedModCount = modCount;

        Itr() {}

        public boolean hasNext() {
            //当索引迭代到size,则表明已经迭代结束
            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();
            }
        }

        @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() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

使用迭代器,我们可以对list中元素进行遍历。

五、易错点

1、关于ArrayList的元素删除问题

①、使用for循环正序遍历list时,连续重复的元素只会删除第一个,无法全部删除

        ArrayList list = new ArrayList<String>(4);
        list.add("a");
        list.add("a");
        list.add("c");
        list.add("d");
        for (int i = 0; i <list.size() ; i++) {
            if ("a".equals(list.get(i))){
                list.remove(i);
            }
        }
        System.out.println(Arrays.toString(list.toArray()));

想必应该有读者会认为结果是[c, d],但是结论刚刚已经总结了,这段程序的最终结果是[a, c, d],现在来分析下产生这种情况的原因。让我们根据remove方的具体实现分析下,当遍历时索引指到下标为0的元素时,发现是“a”,此处元素应该被删除,根据remove的方法实现细节,删除位置后面的元素要向前移动,移动之后“a”后面的“a”元素下标变成了0,后面的元素下标也依次减1,这是在 i = 0时循环的操作。在下一次循环中 i = 1,第二个 “a” 元素就被遗漏了,所以这种删除方法在删除连续重复元素时会有问题。
在这里插入图片描述
那么问题来了,如何解决这个问题,难道在这种普通for循环遍历中就真的无法删除连续重复的元素了吗,解决方法是有的,注意本小节开头说的正序删除会存在问题,相反 逆序遍历就不会存在这种问题,其中原因,聪明的读者可以通过画图就能很快明白其中缘由,这里就暂不累赘了。
②、使用迭代器或者foreach循环遍历时,通过list.remove()删除元素,会抛出异常ConcurrentModificationException

        ArrayList list = new ArrayList<String>(4);
        list.add("a");
        list.add("a");
        list.add("c");
        list.add("d");

        Iterator iterator = list.iterator();
        while (iterator.hasNext()){
            String next = (String)iterator.next();
            if ("a".equals(next)) {
                list.remove(next);
            }
        }
2、ArrayList线程不安全

通过阅读ArrayList源码发现,所有涉及到对elementData数组的修改都没有确保多线程并发的安全性,所以ArrayList不能作为多线程下的共享变量,同时java也提供了线程安全的list-Vector,所有会产生线程安全问题的方法都加上了synchronized关键字。

3、使用情景

适合查询多,增删少,因为增删会涉及到数组的拷贝,耗性能,查询时间复杂度O(1),增删时间复杂度O(n)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值