每天读点java源码——ArrayList

读注释

惯例,先看看类的注释:

Resizable-array implementation of the {@code List} interface. Implements all optional list operations, and permits all elements, including {@code null}. In addition to implementing the {@code List} interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to {@code Vector}, except that it is unsynchronized.)

上来第一句,ArrayList是实现了List接口的可变大小数组,实现了所有可选操作,允许包括null在内的所有元素。ArrayList可以内部改变数组大小,它与Vector很像,不同的是ArrayList不是线程安全的。
其他的注释与LinkedList类似,不再赘述。

读源码

先看看类定义:

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable,java.io.Serializable { }

这里的RandomAccess是一个标记接口,标识当前集合可以进行随机存取操作。

类的一些属性

	/**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;
    
    /**
     * 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 = {};

    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA={};

    transient Object[] elementData;

数组初始化容量DEFAULT_CAPACITY为10,size为数组中元素的个数。DEFAULTCAPACITY_EMPTY_ELEMENTDATA为初始化ArrayList时没有指定list大小而创建的一个默认容量的数组,EMPTY_ELEMENTDATA为指定了list大小时创建的一个具有给定大小的数组。

构造函数

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

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

public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // defend against c.toArray (incorrectly) not returning 				// Object[]
            // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, 							Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
}

ArrayList提供三个构造函数,第一个提供初始化容量,如果在创建ArrayList实例时知道元素大概的数量,建议使用此构造函数提供初始化容量,避免后期的多次扩容带来的性能损失;第二个无参构造函数,创建一个容量为10的默认大小的数组;第三个可以提供一个包含元素的集合来创建一个新的ArrayList实例。

调整集合容器的大小

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

public void ensureCapacity(int minCapacity) {
        if (minCapacity > elementData.length
            && !(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
                 && minCapacity <= DEFAULT_CAPACITY)) {
            modCount++;
            grow(minCapacity);
        }
}

trimToSize()将集合的容量缩小到里面存放的元素个数大小。比如我们初始化的容量是10,里面存了一个元素,调用trimToSize后容量变为1。相反,ensureCapacity()则是将数组扩大到某一个容量,此容量必须大于容器中已有元素的个数。

public int size() {
        return size;
}

public boolean isEmpty() {
        return size == 0;
}

这两个方法没什么可说的,返回数组中元素的个数,判断列表是否为空。

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

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,都是遍历数组的操作。indexOf()与lastIndexOf()区别在于,如果数组中含有多个重复的元素,indexOf返回第一个该元素的位置,而lastIndexOf返回最后一个该元素的位置。

列表转数组

public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
}

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

ArrayList提供了两个将列表转为数组的方法,第一个返回的只能是Object[]类型的数组,第二个可以指定返回的数组类型,不用我们去强转,同时会把列表中的元素放入你传入的数组T[]中。

设置 or 获取 元素

public E get(int index) {
        Objects.checkIndex(index, size);
        return elementData(index);
}

public E set(int index, E element) {
        Objects.checkIndex(index, size);
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
}

get方法获取指定索引位置上的元素,如果超过了列表的索引范围会抛出IndexOutOfBoundsException异常;set方法将给定索引位置上的元素替换为新值,同时会返回旧值。

添加元素

public boolean add(E e) {
        modCount++;
        add(e, elementData, size);
        return true;
}

private void add(E e, Object[] elementData, int s) {
        if (s == elementData.length)
            elementData = grow();
        elementData[s] = e;
        size = s + 1;
}

public void add(int index, E element) {
        rangeCheckForAdd(index);
        modCount++;
        final int s;
        Object[] elementData;
        if ((s = size) == (elementData = this.elementData).length)
            elementData = grow();
        System.arraycopy(elementData, index,
                         elementData, index + 1,
                         s - index);
        elementData[index] = element;
        size = s + 1;
}

第一种add()在列表末尾增加一个元素,如果列表容量不足,会将容量扩大为当前的1.5倍;第二种add(index, element)在指定位置添加元素,如果指定的位置超过列表最大的索引则会抛出IndexOutOfBoundsException

删除元素

public E remove(int index) {
        Objects.checkIndex(index, size);
        final Object[] es = elementData;

        @SuppressWarnings("unchecked") E oldValue = (E) es[index];
        fastRemove(es, index);

        return oldValue;
}

public boolean remove(Object o) {
        final Object[] es = elementData;
        final int size = this.size;
        int i = 0;
        found: {
            if (o == null) {
                for (; i < size; i++)
                    if (es[i] == null)
                        break found;
            } else {
                for (; i < size; i++)
                    if (o.equals(es[i]))
                        break found;
            }
            return false;
        }
        fastRemove(es, i);
        return true;
}

private void fastRemove(Object[] es, int i) {
        modCount++;
        final int newSize;
        if ((newSize = size - 1) > i)
            System.arraycopy(es, i + 1, es, i, newSize - i);
        es[size = newSize] = null;
}

public void clear() {
        modCount++;
        final Object[] es = elementData;
        for (int to = size, i = size = 0; i < to; i++)
            es[i] = null;
}

remove(int index)删除给定位置上的元素,并返回删除的元素;remove(Object)删除指定的元素,如果该元素存在,返回true,不存在返回false,二者的本质都是调用了fastRemove()方法,将待删除元素之后的元素都前移一个位置,由此可见,删除一个元素的时间复杂度为O(n);clear()比较简单,清除数组中所有元素

批量添加元素

public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        modCount++;
        int numNew = a.length;
        if (numNew == 0)
            return false;
        Object[] elementData;
        final int s;
        if (numNew > (elementData = this.elementData).length - (s = size))
            elementData = grow(s + numNew);
        System.arraycopy(a, 0, elementData, s, numNew);
        size = s + numNew;
        return true;
}

public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);

        Object[] a = c.toArray();
        modCount++;
        int numNew = a.length;
        if (numNew == 0)
            return false;
        Object[] elementData;
        final int s;
        if (numNew > (elementData = this.elementData).length - (s = size))
            elementData = grow(s + numNew);

        int numMoved = s - index;
        if (numMoved > 0)
            System.arraycopy(elementData, index,
                             elementData, index + numNew,
                             numMoved);
        System.arraycopy(a, 0, elementData, index, numNew);
        size = s + numNew;
        return true;
}

这两个批量添加元素的不同在于,第一个addAll是在列表的末尾添加n个元素,第二个是在指定的位置开始添加n个元素。可以看出来,在指定位置添加n个元素分三步,①将原始列表长度扩大到size+n,②将指定位置之后的元素向后移动n个位置,③将这n个元素插入指定位置。

批量删除元素

public boolean removeAll(Collection<?> c) {
        return batchRemove(c, false, 0, size);
}
public boolean retainAll(Collection<?> c) {
        return batchRemove(c, true, 0, size);
}

boolean batchRemove(Collection<?> c, boolean complement,
                        final int from, final int end) {
        Objects.requireNonNull(c);
        final Object[] es = elementData;
        int r;
        // Optimize for initial run of survivors
        for (r = from;; r++) {
            if (r == end)
                return false;
            if (c.contains(es[r]) != complement)
                break;
        }
        int w = r++;
        try {
            for (Object e; r < end; r++)
                if (c.contains(e = es[r]) == complement)
                    es[w++] = e;
        } catch (Throwable ex) {
            // Preserve behavioral compatibility with 								// AbstractCollection,
            // even if c.contains() throws.
            System.arraycopy(es, r, es, w, end - r);
            w += end - r;
            throw ex;
        } finally {
            modCount += end - w;
            shiftTailOverGap(es, w, end);
        }
        return true;
}

removeAll()从列表中删除集合C中包含的所有元素,retainAll()从列表中删除集合C中不包含的所有元素,也就是集合C中有的元素都保留下来。二者最终调用的方法都是batchRemove()方法,其基本步骤是:在列表中找到集合C中包含的第一个元素,然后将列表后面的元素覆盖需要移除的列表中的元素,最后将多出来的空位值为null,也就是这里的shiftTailOverGap()方法。

遍历forEach

public void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        final Object[] es = elementData;
        final int size = this.size;
        for (int i = 0; modCount == expectedModCount && i < size; i++)
            action.accept(elementAt(es, i));
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
}

此方法java 1.8之后才有,接受一个Consumer,我们只需要在其accept方法内部实现我们需要的操作就好。

排序

public void sort(Comparator<? super E> c) {
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, size, c);
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        modCount++;
}

这个也是jdk1.8以后增加的,内部的排序用的是Arrays.sort(),也就是归并排序

猜你喜欢

转载自blog.csdn.net/chenshufeng115/article/details/95082369