[JAVA基础] 2、ArrayList源码分析

ArrayList继承图

直接继承了AbstractList抽象类,实现了RandomAccess,Serializable,Cloneable接口

AbstractList:对List接口的简单部分实现。
RandomAccess:标识类是否可以随机访问。
Serializable:标识类是否可以序列化与反序列化,实现了Serializable接口的类可以被ObjectOutputStream转换为字节流,同时也可以通过ObjectInputStream再将其解析为对象。
Cloneable:标识类是否可以使用Object的clone()。
在这里插入图片描述

ArrayList相关属性

/**
    /**
     * 默认初始容量大小
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 空数组数据
     */
    private static final Object[] EMPTY_ELEMENTDATA = {
    
    };

    /**
     * 默认容量为空的数组,以跟EMPTY_ELEMENTDATA区分开,当不对容量进行赋值的时候使用
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {
    
    };

    /**
     * 元素数据
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * list大小
     */
    private int size;

以及AbstractList继承的属性

// 用来标识List的结构改变次数
protected transient int modCount = 0;

构造器

ArrayList()

当new ArrayList()时执行该构造器

	public ArrayList() {
    
    
		// 赋值为默认空数据
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

ArrayList(int initialCapacity)

当执行new ArrayList(10)时执行该构造器

	public ArrayList(int initialCapacity) {
    
    
		// 如果容量大小大于0,new 一个Object的数组
        if (initialCapacity > 0) {
    
    
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
    
    
        	// 容量等于0,赋值为EMPTY_ELEMENTDATA
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
    
    
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

ArrayList(Collection<? extends E> c)

传递一个容器接口的实现类给构造器,根据其实现构建ArrayList

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

相关方法

在这里插入图片描述

trimToSize

修剪list大小,如果size小于elementData数组的长度,那么修改elementData的长度到size长度。

    public void trimToSize() {
    
    
    	// 修改了数组结构
        modCount++;
        if (size < elementData.length) {
    
    
        	// 如果size=0则为EMPTY_ELEMENTDATA,否则赋值为size大小的数组
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              // Array.copyOf(从elementData中复制size长度的数组)
              : Arrays.copyOf(elementData, size);
        }
    }

ensureCapacity

预设ArrayList的大小,当ArrayList的容量较大时,可以加快速率,外部调用。如果要扩容调用ensureExplicitCapacity

    public void ensureCapacity(int minCapacity) {
    
    
        // 最小扩展值
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
            // any size if not default element table
            ? 0
            // larger than default for default empty table. It's already
            // supposed to be at default size.
            : DEFAULT_CAPACITY;

        // 如果最小容量值大于最小扩展值,才需要确保显式容量
        if (minCapacity > minExpand) {
    
    
        	// 确认显式的容量
            ensureExplicitCapacity(minCapacity);
        }
    }

ensureCapacityInternal

确保内部容量,内部方法调用,如果要扩容调用ensureExplicitCapacity

    private void ensureCapacityInternal(int minCapacity) {
    
    
        // 如果最开始为默认空数组,则默认大小为10
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
    
    
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

ensureExplicitCapacity

确保显式容量,如果需要扩容则调用grow方法

    private void ensureExplicitCapacity(int minCapacity) {
    
    
        modCount++;

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

grow

扩容方法,默认扩容1.5倍,如果1.5倍不够或者溢出(为负数)则赋值为minCapacity,如果newCapacity 大于Integer.MAX_VALUE - 8则调用hugeCapacity方法获得大容量的值。

	private void grow(int minCapacity) {
    
    
        // overflow-conscious code
        int oldCapacity = elementData.length;
        // 1.5倍旧容量大小
        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);
    }

hugeCapacity

返回容器大容量时的容量值,一般返回Integer.MAX_VALUE

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

size

返回列表大小。

	public int size() {
    
    
        return size;
    }

isEmpty

判断列表是否为空,直接判断size是否等于0

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

contains

判断列表是否包含某个元素,通过indexOf方法判断,如果其值大于等于0表示存在。

	public boolean contains(Object o) {
    
    
        return indexOf(o) >= 0;
    }

indexOf

返回指定元素所在的索引值,如果元素不存在则返回-1

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

lastIndexOf

返回指定元素所在的最后一个索引值,如果元素不存在则返回-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;
    }

clone

克隆,只有实现了Cloneable接口的才能使用,先调用Object的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);
        }
    }

toArray

将列表转化为数组,直接调用了Arrays.copyOf方法

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

toArray(T[] a)

将列表转化为指定类型的数组

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

elementData

获取指定索引处的元素

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

get

先检查index是否在范围中,然后返回值

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

        return elementData(index);
    }

set

返回旧值,并设置新值

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

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

add

添加一个元素到列表中,modCount会增加。先检查容量是否足够。

	public boolean add(E e) {
    
    
        // 检查内部容量
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

add(int index, E element)

在指定索引处添加元素

	public void add(int index, E element) {
    
    
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        // 从elementData的index位置开始复制size-index个元素到elementData的index+1位置
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

remove

移除指定索引处的元素,modCount会增加

	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)

移除指定元素,modCount增加。如果元素为null,遍历一次,判断是否有值为null,然后删除;如果元素不为null,使用equals判断是否有元素相同,然后调用fastRemove方法删除。

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

fastRemove

删除对象实现方法,modCount增加

	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
    }

clear

清理所有elementData数据方法,modCount增加

	public void clear() {
    
    
        modCount++;

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

        size = 0;
    }

addAll

添加Collection接口实现类中的所有元素,如果容量不够会modCount增加扩容。先判断确保容量大小是否足够,然后调用System.arraycopy复制。

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

addAll(int index, Collection<? extends E> c)

在指定索引处,插入Collection接口实现类中的所有数据。如果容量不够会modCount增加扩容

	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)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);

        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }

removeRange

删除指定fromIndex到toIndex中的数据,modCount增加

	protected void removeRange(int fromIndex, int toIndex) {
    
    
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
    
    
            elementData[i] = null;
        }
        size = newSize;
    }

removeAll

从本ArrayList中移除Collection接口实现类中所有的对象。调用batchRemove方法

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

retainAll

保留本ArrayList在Collection接口实现类中存在的对象。调用batchRemove方法

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

batchRemove

批量移动,modCount += size - w。w为符合条件的元素数量,可能是需要移除的,可能是需要保留的。

	private boolean batchRemove(Collection<?> c, boolean complement) {
    
    
        final Object[] elementData = this.elementData;
        // r表示读取的数据数量,w表示写的数据数量
        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.
            // 没有读取完,直接把后面的元素放置w后面
            if (r != size) {
    
    
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            // 如果w跟size不同
            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;
    }

writeObject

写对象到ObjectOutputStream中

readObject

从ObjectInputStream中读取对象

listIterator(int index)

返回从指定index开始的一个列表迭代器。

	public ListIterator<E> listIterator(int index) {
    
    
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

listIterator

返回从0开始的列表迭代器。

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

iterator

返回一个迭代器。

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

subList

返回一个子列表

	public List<E> subList(int fromIndex, int toIndex) {
    
    
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, 0, fromIndex, toIndex);
    }

内部类

ArrayList.java中包含的内部类。

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
        int expectedModCount = modCount;

        public boolean hasNext() {
    
    
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        // 先获取cursor数据,再cursor加1
        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];
        }

        // 先删除lastRet,再cursor=lastRet,因为lastRet删除了,所以lastRet的值就是后续的值
        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();
        }
    }

ListItr

列表迭代器实现类

	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;
            if (i < 0)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            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();
            }
        }

        // 在cursor位置添加元素,然后cursor+1
        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();
            }
        }
    }

SubList

子列表实现类

	private class SubList extends AbstractList<E> implements RandomAccess {
    
    
        private final AbstractList<E> parent;
        // 相对于上一级的偏移量
        private final int parentOffset;
        // 相对于ArrayList的偏移量
        private final int offset;
        int size;
        // ……省略
    }

ArrayListSpliterator

ArrayList分离器

	static final class ArrayListSpliterator<E> implements Spliterator<E> {
    
    

        private final ArrayList<E> list;
        private int index; // current index, modified on advance/split
        // 直到使用前都为-1,否则为最后一个索引
        private int fence; // -1 until used; then one past last index
        // fence 设置时初始化
        private int expectedModCount; // initialized when fence set

        /** Create new spliterator covering the given  range */
        ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
                             int expectedModCount) {
    
    
            this.list = list; // OK if null unless traversed
            this.index = origin;
            // fence 一般等于list.size()
            this.fence = fence;
            this.expectedModCount = expectedModCount;
        }

        private int getFence() {
    
     // initialize fence to size on first use
            int hi; // (a specialized variant appears in method forEach)
            ArrayList<E> lst;
            if ((hi = fence) < 0) {
    
    
                if ((lst = list) == null)
                    hi = fence = 0;
                else {
    
    
                    expectedModCount = lst.modCount;
                    hi = fence = lst.size;
                }
            }
            return hi;
        }

        // 尝试分一半
        public ArrayListSpliterator<E> trySplit() {
    
    
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid) ? null : // divide range in half unless too small
                new ArrayListSpliterator<E>(list, lo, index = mid,
                                            expectedModCount);
        }

        // 尝试使index的元素执行action.accept,然后index+1
        public boolean tryAdvance(Consumer<? super E> action) {
    
    
            if (action == null)
                throw new NullPointerException();
            int hi = getFence(), i = index;
            if (i < hi) {
    
    
                index = i + 1;
                @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
                action.accept(e);
                if (list.modCount != expectedModCount)
                    throw new ConcurrentModificationException();
                return true;
            }
            return false;
        }

		// 对剩余的元素执行action.accept
        public void forEachRemaining(Consumer<? super E> action) {
    
    
            int i, hi, mc; // hoist accesses and checks from loop
            ArrayList<E> lst; Object[] a;
            if (action == null)
                throw new NullPointerException();
            if ((lst = list) != null && (a = lst.elementData) != null) {
    
    
                if ((hi = fence) < 0) {
    
    
                    mc = lst.modCount;
                    hi = lst.size;
                }
                else
                    mc = expectedModCount;
                if ((i = index) >= 0 && (index = hi) <= a.length) {
    
    
                    for (; i < hi; ++i) {
    
    
                        @SuppressWarnings("unchecked") E e = (E) a[i];
                        action.accept(e);
                    }
                    if (lst.modCount == mc)
                        return;
                }
            }
            throw new ConcurrentModificationException();
        }

        // 预计大小
        public long estimateSize() {
    
    
            return (long) (getFence() - index);
        }
		
		// 分离器的特征
        public int characteristics() {
    
    
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_43621091/article/details/110144645