ArrayList源码分析

211 阅读8分钟

1.成员变量与构造方法

// ArrayList的默认大小为10
private static final int DEFAULT_CAPACITY = 10;
// 定义容量为0时,集合存储元素的数组
private static final Object[] EMPTY_ELEMENTDATA = {};
// 定义默认容量时,集合存储元素的数组
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
// 定义当前集合存储元素的数组
transient Object[] elementData;
// 定义集合的长度
private int size;

// 自定义容量的构造方法
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) {
        // 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;
    }
}

2.add()

新增方法步骤:
1.确保容量充足
2.将元素放入数组的最后一位, 集合长度+1
3.返回结果
public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
}

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

计算所需容量:如果存储元素的数组为空,容量为默认值10,否则容量为(当前存储元素的数组大小+1)
private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
}
是否需要扩容:如果当前所需容量大于存储元素的数组长度,才会扩容
private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

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

扩容方法:默认扩容0.5倍,如果新的容量还不够,会继续扩大容量,最大容量为Integer最大值(2的31次方-1)
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);
 }

 private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
 }

3.remove()

remove(int index)方法:
1.检查下标是否合法
2.计算移动位数
3.将删除元素之后的元素向前移动
4.存储集合长度减一,并将存储元素数组的最后以为置空
5.返回删除的元素
 public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = 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(Object o)方法:
1.根据值找到下标
2.计算移动位数
3.将删除元素之后的元素向前移动
4.存储集合长度减一,并将存储元素数组的最后以为置空
5.返回删除的元素
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
}

4.clear()

// clear(): 将存储元素的数组的所有元素置空,集合的长度设为0
public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
}

5.addAll()

addAll:
1.将集合转成数组
2.扩容
3.将新数组的元素添加到集合数组里面
4.增加集合长度
5.返回结果
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;
}

6.retainAll()

retainAll:获取两个集合的交集
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++)
                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;
            }
            // 公有的元素的个数与当前集合的个数不相等,返回true,否则返回false
            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;
}

7.contains(), indexOf(), lastIndexOf()

// ArrayList的contains(), indexOf(), lastIndexOf()是在for循环里面一个一个找,数据量大时,效率比较低,尽量不要使用
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;
}

8.clone()

// ArrayList重写clone(),属于深度克隆
public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
}

9.toArray()

// toArray(),实际是将当前集合的数组属性复制了一份
public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
}

10.set()

// set()返回的是原来的值
public E set(int index, E element) {
        rangeCheck(index);
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
}

11.iterator(), listIterator()

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

public ListIterator<E> listIterator() {
        return new ListItr(0);
}

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;

        Itr() {}
        // 判断是否有下一个元素
        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];
        }
        // 调用remove()前,必须调用next(),否则lastRet < 0, 从而导致会报IllegalStateException
        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;
            // 如果当前游标大于集合长度,会抛出ConcurrentModificationException
            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;
            // 检查处理次数是否正常,如果不正常,抛出ConcurrentModificationException
            checkForComodification();
        }

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

private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }
        // 是否有上一个元素
        public boolean hasPrevious() {
            return cursor != 0;
        }
        // 返回下一个元素的索引
        public int nextIndex() {
            return cursor;
        }

        // 返回返回上一个元素的索引
        public int previousIndex() {
            return cursor - 1;
        }

        // 返回上一个元素
        @SuppressWarnings("unchecked")
        public E previous() {
            checkForComodification();
            int i = cursor - 1;
            // 如果上一个元素不存在,抛出NoSuchElementException
            if (i < 0)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            // 如果上一个元素的索引大于等于集合长度,抛出ConcurrentModificationException, 由于多线程并发导致获取的索引有问题
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i;
            return (E) elementData[lastRet = i];
        }
        // 替换元素
        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        // 新增元素
        public void add(E e) {
            checkForComodification();

            try {
                int i = cursor;
                ArrayList.this.add(i, e);
                cursor = i + 1;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
}
Iterator与ListIterator的区别:
1. Iterator有remove(), forEachRemaining(), ListIterator没有
2.ListIterator有add(), set(), 能获取上一个元素,Iterator不能
3.ListIterator可以通过previousIndex(), nextIndex()获取索引,Iterator不能

12.forEach()

public void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        // 获取当前集合存储元素的数组
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int size = this.size;
        // 消费者迭代消费数组的元素
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
}
List<String> list = Arrays.asList("1", "2", "3");
// 输出
list.forEach(System.out::println);
list.forEach((a) -> {
	// 业务逻辑代码
});

13.asList()的坑

public static <T> List<T> asList(T... a) {
	        return new ArrayList<>(a);
}
private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable
	    {
	        private static final long serialVersionUID = -2764017481108945198L;
	        private final E[] a;
	
	        ArrayList(E[] array) {
	            a = Objects.requireNonNull(array);
	        }
	
	        @Override
	        public int size() {
	            return a.length;
	        }
	
	        @Override
	        public Object[] toArray() {
	            return a.clone();
	        }
	
	        @Override
	        @SuppressWarnings("unchecked")
	        public <T> T[] toArray(T[] a) {
	            int size = size();
	            if (a.length < size)
	                return Arrays.copyOf(this.a, size,
	                                     (Class<? extends T[]>) a.getClass());
	            System.arraycopy(this.a, 0, a, 0, size);
	            if (a.length > size)
	                a[size] = null;
	            return a;
	        }
	
	        @Override
	        public E get(int index) {
	            return a[index];
	        }
	
	        @Override
	        public E set(int index, E element) {
	            E oldValue = a[index];
	            a[index] = element;
	            return oldValue;
	        }
	
	        @Override
	        public int indexOf(Object o) {
	            E[] a = this.a;
	            if (o == null) {
	                for (int i = 0; i < a.length; i++)
	                    if (a[i] == null)
	                        return i;
	            } else {
	                for (int i = 0; i < a.length; i++)
	                    if (o.equals(a[i]))
	                        return i;
	            }
	            return -1;
	        }
	
	        @Override
	        public boolean contains(Object o) {
	            return indexOf(o) != -1;
	        }
	
	        @Override
	        public Spliterator<E> spliterator() {
	            return Spliterators.spliterator(a, Spliterator.ORDERED);
	        }
	
	        @Override
	        public void forEach(Consumer<? super E> action) {
	            Objects.requireNonNull(action);
	            for (E e : a) {
	                action.accept(e);
	            }
	        }
	
	        @Override
	        public void replaceAll(UnaryOperator<E> operator) {
	            Objects.requireNonNull(operator);
	            E[] a = this.a;
	            for (int i = 0; i < a.length; i++) {
	                a[i] = operator.apply(a[i]);
	            }
	        }
	
	        @Override
	        public void sort(Comparator<? super E> c) {
	            Arrays.sort(a, c);
	        }
}
// AbstractList中的remove(),add()
public E remove(int index) {
	   throw new UnsupportedOperationException();
}
	    
public boolean add(E e) {
	   add(size(), e);
	   return true;
}
	    
public void add(int index, E element) {
	   throw new UnsupportedOperationException();
}

总结:Arrays中的ArrayList继承AbstractList,没有重写remove()和add(),当list1调用remove和add实际执行的是AbstractList中的remove和add,因此会报UnsupportedOperationException,可以通过下面方式替换:
List<String> list2 = Arrays.stream(new String[]{"1", "2"}).collect(Collectors.toList());

14.subList的坑

ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
List<String> list1 = list.subList(0, 1);
list1.add("4");
list.forEach(System.out::println); // 结果: 1 2 3 4
list.add("5"); // 报ConcurrentModificationException

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;
        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;
            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 E get(int index) {
            rangeCheck(index);
            checkForComodification();
            return ArrayList.this.elementData(offset + index);
        }

        public int size() {
            checkForComodification();
            return this.size;
        }

        .....
}
总结:使用subList, 操作获得的list会影响原来的list,操作原来的list会报ConcurrentModificationException,因为sublist只是获取原来list部分元素的引用,而不是产生新的list,可以通过下面方式替换:
List<String> newList = list.stream().skip(2).collect(Collectors.toList());
List<String> newList2 = list.stream().limit(2).collect(Collectors.toList());