java源码分析---ArrayList类(JDK14)


更多源码分析,请点击


ArrayList

ArrayList 执行效率高,但是线程不安全。相当于一个可变长度数组(顺序列表),可以通过下标索引直接对元素进行访问,但是插入和删除效率较低。

ArrayList 底层采用 Object 数组来保存数据,所以如果要保存基本类型需要使用他们的包装类。

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final int DEFAULT_CAPACITY = 10;
    @java.io.Serial
    private static final long serialVersionUID = 8683452581122892189L; //序列化ID
    private static final Object[] EMPTY_ELEMENTDATA = {};
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    transient Object[] elementData; // non-private to simplify nested class access
    private int size;
}

ArrayList 类继承自 AbstractList 类,实现了 ListRandomAccessCloneableSerializable 接口。

DEFAULT_CAPACITYArrayList 对象的默认长度。

EMPTY_ELEMENTDATA 是一个空的 Object 数组。

DEFAULTCAPACITY_EMPTY_ELEMENTDATA 是一个空的 Object 数组,当创建 ArrayList 对象时,如果没有指定列表容量,将 elementData 初始化为该空数组。

elementData 用于保存列表中元素的 Object 数组。

size 用来保存当前列表中元素的数量。

ArrayList()

初始化构造一个空的ArrayList对象。

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

ArrayList(Int)

初始化构造一个容量大小为 initialCapacity 的ArrayList对象。

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

ArrayList(Collection<? extends E> c)

创建一个ArrayList对象,初始化内容为集合 c 中的元素。

  • 将集合 c 转换为数组 a,如果数组长度大于零且 c 也是 ArrayList 对象,则将数组 a 直接赋给 elementData。
  • 如果集合 c 不是 ArrayList 对象,则将数组 a 拷贝一份赋值给 elementData。
  • 如果数组长度为零,初始化为空。
public ArrayList(Collection<? extends E> c) {
    Object[] a = c.toArray();
    if ((size = a.length) != 0) {
        if (c.getClass() == ArrayList.class) {
            elementData = a;
        } else {
            elementData = Arrays.copyOf(a, size, Object[].class);
        }
    } else {
        // replace with empty array.
        elementData = EMPTY_ELEMENTDATA;
    }
}

trimToSize()

将当前列表的容量调整为列表的实际大小。

  • modCount 是记录列表结构被修改的次数,定义在父类 AbstractList 中。
  • 将列表按照实际存储元素的数量拷贝一份返回。
public void trimToSize() {
    modCount++;
    if (size < elementData.length) {
        elementData = (size == 0)
          ? EMPTY_ELEMENTDATA
          : Arrays.copyOf(elementData, size);
    }
}

ensureCapacity(int)

确保数组中最少可以存放 minCapacity 个元素。

如果 minCapacity 大于当前列表长度,需要调用 grow 方法进行扩容。

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

grow(minCapacity)

对列表进行扩容,确保列表中最少可以存放 minCapacity 个元素。

private Object[] grow(int minCapacity) {
    int oldCapacity = elementData.length;
    if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        int newCapacity = ArraysSupport.newLength(oldCapacity,
                minCapacity - oldCapacity, /* minimum growth */
                oldCapacity >> 1           /* preferred growth */);
        return elementData = Arrays.copyOf(elementData, newCapacity);
    } else {
        return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
    }
}

分析

  • 如果当前数组 elementData 为空,则创建一个大小为 max(DEFAULT_CAPACITY, minCapacity) 的数组赋给 elementData
  • 如果当前数组 elementData 不为空,首先调用 ArraysSupport.newLength() 方法计算数组的新长度。
    • 默认对数组的扩容长度为数组原来长度 oldCapacity 的一半。如果这样依然小于 minCapacity ,那数组的新长度为 minCapacity
    • 如果 newLength 大于 MAX_ARRAY_LENGTH ,调用 hugeLength() 方法进行处理。
    • hugeLength() 方法中,使扩容后的大小为 minCapacity,即满足要求的最小长度。
    • 如果 minCapacity 为负数,即溢出,大于 int 的表示范围,抛出异常。
    • 否则,如果小于等于 MAX_ARRAY_LENGTH ,返回 MAX_ARRAY_LENGTH
    • 如果大于 MAX_ARRAY_LENGTH ,返回 Integer.MAX_VALUE

思考 :为什么 MAX_ARRAY_LENGTH = Integer.MAX_VALUE - 8 ?

点此查看解析

public static final int MAX_ARRAY_LENGTH = Integer.MAX_VALUE - 8; //数组最大长度

public static int newLength(int oldLength, int minGrowth, int prefGrowth) {
    // assert oldLength >= 0
    // assert minGrowth > 0

    int newLength = Math.max(minGrowth, prefGrowth) + oldLength;
    if (newLength - MAX_ARRAY_LENGTH <= 0) {
        return newLength;
    }
    return hugeLength(oldLength, minGrowth); //如果数组的长度大于 MAX_ARRAY_LENGTH ,调用该方法
}

private static int hugeLength(int oldLength, int minGrowth) {
    int minLength = oldLength + minGrowth;
    if (minLength < 0) { // overflow
        throw new OutOfMemoryError("Required array length too large");
    }
    if (minLength <= MAX_ARRAY_LENGTH) {
        return MAX_ARRAY_LENGTH;
    }
    return Integer.MAX_VALUE;
}

grow()

对当前列表进行扩容,扩容后的最小长度为 size+1 ,调用 grow(int) 方法实现。

private Object[] grow() {
    return grow(size + 1);
}

size()

返回当前列表中元素的数量。

public int size() {
    return size;
}

isEmpty()

判断当前列表中是否包含元素。

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

contains(Object)

判断当前列表中是否包含指定元素 o

调用 indexOf(Object) 方法实现,即查找该元素在列表中的索引,如果索引大于等于零,即包含该元素。

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

indexOf(Object)

返回指定元素 o 在列表中的第一个位置索引,如果列表中没有该元素,返回 -1 。

调用 indexOfRange() 方法实现在列表索引区间 [0, size) 中查找指定元素 o 的第一个索引。

public int indexOf(Object o) {
    return indexOfRange(o, 0, size);
}

indexOfRange(Object, int, int)

默认方法,在列表索引区间 [start, end) 中查找指定元素 o 的第一个索引,如果列表中没有该元素,返回 -1 。

对区间 [start, end) 逐个遍历与元素 o 进行比较,如果相等,返回索引。

注意 :这里的比较应该使用 equals(Object) 方法,这样比较的是内容,== 比较的是地址。

int indexOfRange(Object o, int start, int end) {
    Object[] es = elementData;
    if (o == null) {
        for (int i = start; i < end; i++) {
            if (es[i] == null) {
                return i;
            }
        }
    } else {
        for (int i = start; i < end; i++) {
            if (o.equals(es[i])) {
                return i;
            }
        }
    }
    return -1;
}

lastIndexOf(Object)

返回指定元素 o 在列表中的最后一个位置索引,如果列表中没有该元素,返回 -1 。

调用 lastIndexOfRange() 方法实现在列表索引区间 [0, size) 中查找指定元素 o 的最后一个索引。

public int lastIndexOf(Object o) {
    return lastIndexOfRange(o, 0, size);
}

lastIndexOfRange(Object, int, int)

默认方法,在列表索引区间 [start, end) 中查找指定元素 o 的最后一个索引,如果列表中没有该元素,返回 -1 。

对区间 [start, end) 中的元素从后往前逐个遍历与元素 o 进行比较,如果相等,返回索引。

注意 :这里的比较应该使用 equals(Object) 方法,这样比较的是内容,== 比较的是地址。

int lastIndexOfRange(Object o, int start, int end) {
    Object[] es = elementData;
    if (o == null) {
        for (int i = end - 1; i >= start; i--) {
            if (es[i] == null) {
                return i;
            }
        }
    } else {
        for (int i = end - 1; i >= start; i--) {
            if (o.equals(es[i])) {
                return i;
            }
        }
    }
    return -1;
}

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()

返回一个包含此列表中所有元素的数组,调用数组拷贝函数将当前列表的 elementData 数组拷贝一份返回。

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

toArray(T[])

将列表中的所有元素保存在指定的数组 a 中,如果数组 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(int)

默认方法,返回 elementData 数组指定索引 index 处的元素。

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

elementAt(Object[], int)

静态默认方法,返回指定数组 es 中指定索引 index 处的元素。

static <E> E elementAt(Object[] es, int index) {
    return (E) es[index];
}

get(int)

返回当前列表中指定索引 index 处的元素。

  • 先检查索引是否越界,然后直接调用 elementData() 方法返回索引 index 处的元素。
public E get(int index) {
    Objects.checkIndex(index, size);
    return elementData(index);
}

set(int, E)

将当前列表中指定索引 index 处的元素替换为 e

  • 先检查索引是否越界,然后调用 elementData() 方法得到索引 index 处的元素 oldValue
  • 将索引 index 处的元素替换为 e ,返回 oldValue
public E set(int index, E element) {
    Objects.checkIndex(index, size);
    E oldValue = elementData(index);
    elementData[index] = element;
    return oldValue;
}

add(E, Object[], int)

在指定数组 elementData 的指定位置 s 处添加元素 e

  • 如果索引 s 等于数组的长度,即数组越界,需要调用 grow() 方法对数组进行扩容。
  • 将元素 e 添加到数组中,更新数组中元素的数量。
private void add(E e, Object[] elementData, int s) {
    if (s == elementData.length)
        elementData = grow();
    elementData[s] = e;
    size = s + 1;
}

add(E)

将给定元素 e 添加到列表末尾中。调用 add(E, Object[], int) 方法实现。

public boolean add(E e) {
    modCount++;                //因为对数组进行了修改,所以需要对modCount加1
    add(e, elementData, size);
    returnn true;
}

add(int, E)

将指定元素 element 插入到索引 index 处,原来 index 处及之后的元素右移一位。

  • 如果当前列表已经放满了,需要先进行扩容操作。
  • 将 index 之后的元素拷贝到 index+1 处。
  • 将元素 element 添加到数组指定索引处,更新数组中元素的数量。
public void add(int index, E element) {
    rangeCheckForAdd(index); //检查索引 index 是否合法,即 >= 0 && <= size
    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;
}

remove(int)

删除指定索引 index 处的元素,将索引 index 之后的元素左移一位。

  • 先检查索引是否越界,得到索引 index 处的元素 oldValue
  • 调用 fastRemove(Object[], int) 方法将 index 之后的元素左移一位,返回 oldValue
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;
}

fastRemove(Object[] es, int i)

将给定数组 es 中从索引 i 之后的元素左移一位。

  • 如果索引 i 不是数字中最后一个元素,则调用数组拷贝函数将数组中索引在 [i + 1, size) 区间的元素拷贝到 [i, size - 1) 。
  • 将数组中最后一个元素 es[size - 1] 置为空,更新数组长度。
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;
}

equals(Object)

判断当前列表和指定对象 o 是否相等。

  • 如果两个对象地址相等,直接返回 true
  • 如果指定对象 o 不是 List 的子类,返回 false
  • 如果 oArrayList 对象,调用 equalsArrayList() 方法比较;否则,调用 equalsRange() 方法比较。
  • 检查 modCount 是否改变,如果改变了,说明当前列表在比较后发生了改变,抛出异常。
public boolean equals(Object o) {
    if (o == this) {
        return true;
    }

    if (!(o instanceof List)) {
        return false;
    }

    final int expectedModCount = modCount;
    // ArrayList can be subclassed and given arbitrary behavior, but we can
    // still deal with the common case where o is ArrayList precisely
    boolean equal = (o.getClass() == ArrayList.class)
        ? equalsArrayList((ArrayList<?>) o)
        : equalsRange((List<?>) o, 0, size);

    checkForComodification(expectedModCount);
    return equal;
}

equalsRange(List<?>, int, int)

比较当前列表和指定列表 other 中指定区间 [from, to) 的元素是否相等。

  • 从索引 from 开始逐个比较两个列表中的元素是否相等,如果不相等,返回 false
  • objects.equals(Object, Object) 方法比较两个元素是否相等,先比较它们的地址,如果地址不相等比较他们的值。
boolean equalsRange(List<?> other, int from, int to) {
    final Object[] es = elementData;
    if (to > es.length) {
        throw new ConcurrentModificationException();
    }
    var oit = other.iterator();
    for (; from < to; from++) {
        if (!oit.hasNext() || !Objects.equals(es[from], oit.next())) {
            return false;
        }
    }
    return !oit.hasNext();
}

public static boolean equals(Object a, Object b) {
    return (a == b) || (a != null && a.equals(b));
}

equalsArrayList(ArrayList<?>)

比较两个 ArrayList 对象的元素是否相等。

private boolean equalsArrayList(ArrayList<?> other) {
    final int otherModCount = other.modCount;
    final int s = size;
    boolean equal;
    if (equal = (s == other.size)) {
        final Object[] otherEs = other.elementData;
        final Object[] es = elementData;
        if (s > es.length || s > otherEs.length) {
            throw new ConcurrentModificationException();
        }
        for (int i = 0; i < s; i++) {
            if (!Objects.equals(es[i], otherEs[i])) {
                equal = false;
                break;
            }
        }
    }
    other.checkForComodification(otherModCount);
    return equal;
}

hashCode()

返回当前对象的哈希值。

  • 通过逐个计算每个元素的哈希值,通过公式 s [ 0 ] ∗ 3 1 n − 1 + s [ 1 ] ∗ 3 1 n − 2 + . . . + s [ n − 1 ] s[0]*31^{n-1} + s[1]*31^{n-2} + ... + s[n-1] s[0]31n1+s[1]31n2+...+s[n1] 计算
  • 计算完成后,检查 modCount 是否改变,如果改变了,说明当前列表在比较后发生了改变,抛出异常。
public int hashCode() {
    int expectedModCount = modCount;
    int hash = hashCodeRange(0, size);
    checkForComodification(expectedModCount);
    return hash;
}

hashCodeRange(int, int)

计算当前列表区间 [from, to) 中的元素的哈希值。通过公式 s [ 0 ] ∗ 3 1 n − 1 + s [ 1 ] ∗ 3 1 n − 2 + . . . + s [ n − 1 ] s[0]*31^{n-1} + s[1]*31^{n-2} + ... + s[n-1] s[0]31n1+s[1]31n2+...+s[n1] 计算, s[i] 即索引为i的元素的哈希值。

int hashCodeRange(int from, int to) {
    final Object[] es = elementData;
    if (to > es.length) {
        throw new ConcurrentModificationException();
    }
    int hashCode = 1;
    for (int i = from; i < to; i++) {
        Object e = es[i];
        hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode());
    }
    return hashCode;
}

remove(Objet)

删除当前列表中的第一个等于 o 的元素。

  • 先查找出元素 o 在列表中的索引 i ,然后通过 fastRemove() 方法将索引 i 之后的元素左移一位,即删除了元素 o
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;
}

clear()

删除当前列表中的所有元素,即将 elementData 数组中的每个元素都置为 null

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

addAll(Collection<? extends E>)

将集合 c 中的元素全部添加到当前列表中。

  • 将集合 c 中的元素转换为数组形式,如果当前列表容量不足,需要先对列表进行扩容操作。
  • 将数组 a 中的所有元素拷贝到当前列表索引 size 之后,更新 size,即列表存放元素个数。
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;
}

addAll(int, Collection<? extends E>)

将集合 c 中的元素插入到当前列表索引 index 处,将原 index 之后的元素右移 c.size() 位。

  • 将集合 c 中的元素转换为数组形式,如果当前列表容量不足,需要先对列表进行扩容操作。
  • 将当前列表 [index, size) 区间的元素拷贝到 [index + c.size(), size + c.size()] 处。
  • 将数组 a 中的所有元素拷贝到当前列表索引 index 之后,更新 size,即列表存放元素个数。
public boolean addAll(int index, Collection<? extends E> c) {
    rangeCheckForAdd(index); //检查索引 index 是否合法,即 >= 0 && <= size

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

removeRange(int, int)

删除区间 [fromIndex, toIndex) 之间的所有元素。即将索引 toIndex 之后的元素左移 toIndex - fromIndex 位。通过 shiftTailOverGap() 方法实现。

protected void removeRange(int fromIndex, int toIndex) {
    if (fromIndex > toIndex) {
        throw new IndexOutOfBoundsException(
                outOfBoundsMsg(fromIndex, toIndex));
    }
    modCount++;
    shiftTailOverGap(elementData, fromIndex, toIndex);
}

shiftTailOverGap(Object[], int, int)

将数组 es 中索引 hi 之后的元素左移 hi - lo 位。

  • 通过数组拷贝函数将数组 es 中 [lo, es.length) 区间的元素拷贝到 [hi, size - hi] 处。
  • 将索引 size - hi + lo 之后的元素全置为 null
private void shiftTailOverGap(Object[] es, int lo, int hi) {
    System.arraycopy(es, hi, es, lo, size - hi);
    for (int to = size, i = (size -= hi - lo); i < to; i++)
        es[i] = null;
}

removeAll(Collection<?>)

删除当前列表中所有包含在集合 c 中的元素。调用 batchRemove() 方法实现。

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

retainAll(Collection<?>)

仅保留此集合中包含在指定集合中的元素。调用 batchRemove() 方法实现。

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

batchRemove(Collection<?>, boolean, final int, final int)

删除或仅保留当前列表中包含在指定集合中区间 [from, end) 的元素。

  • 如果 complement 的值为 true ,表示仅保留此集合中包含在指定集合 c 中的元素。
  • 如果 complement 的值为 false ,表示删除当前列表中所有包含在集合 c 中的元素。
  • 先逐个判断当前列表的元素是否包含在集合 c 中,找到第一个需要删除的元素的索引 r
  • 然后将列表中满足要求的元素一次存放在索引 r 之后。
  • 在将索引 end 之后的元素移动到索引 w 处,并将索引 end 之后的元素置为 null 。调用 shiftTailOverGap() 方法实现。
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;
}

writeObject(ObjectOutputStream)

将当前列表的内容(长度和元素)写入到输出流中。

private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException {
    // Write out element count, and any hidden stuff
    int expectedModCount = modCount;
    s.defaultWriteObject();

    // Write out size as capacity for behavioral compatibility with clone()
    s.writeInt(size);

    // Write out all elements in the proper order.
    for (int i=0; i<size; i++) {
        s.writeObject(elementData[i]);
    }

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

readObject(ObjectInputStream)

从输入流中读取列表的内容(长度和元素),保存到当前列表中。

private void readObject(java.io.ObjectInputStream s)
    throws java.io.IOException, ClassNotFoundException {

    // Read in size, and any hidden stuff
    s.defaultReadObject();

    // Read in capacity
    s.readInt(); // ignored

    if (size > 0) {
        // like clone(), allocate array based upon size not capacity
        SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, size);
        Object[] elements = new Object[size];

        // Read in all elements in the proper order.
        for (int i = 0; i < size; i++) {
            elements[i] = s.readObject();
        }

        elementData = elements;
    } else if (size == 0) {
        elementData = EMPTY_ELEMENTDATA;
    } else {
        throw new java.io.InvalidObjectException("Invalid size: " + size);
    }
}

listIterator(int)

返回一个列表迭代器,迭代器指向的位置为指定索引 index 处。

public ListIterator<E> listIterator(int index) {
    rangeCheckForAdd(index); //检查索引 index 是否合法,即 index 应该满足 >= 0 && <= size
    return new ListItr(index);
}

listIterator()

返回一个列表迭代器,迭代器指向的位置为索引 0 处。

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

ListItr

列表迭代器的实现类, listIterator()listIterator(int) 方法通过调用该类的构造函数返回一个列表迭代器对象。

该类中提供了 hasPrevious()nextIndex()previousIndex()previous()set(E)add(E) 等方法,同时还继承了 Itr 类中的 hasnext()next()remove()forEachRemaining() 方法,实现了对列表的遍历和元素的修改与添加。

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

    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()

返回当前列表的迭代器对象。

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

Itr

迭代器接口的实现类, iterator() 方法通过调用该类的构造方法返回列表的迭代器对象。

提供了 hasnext()next()remove()forEachRemaining() 方法实现对列表的遍历和删除元素。

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;

    // prevent creating a synthetic constructor
    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];
    }

    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
    public void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int size = ArrayList.this.size;
        int i = cursor;
        if (i < size) {
            final Object[] es = elementData;
            if (i >= es.length)
                throw new ConcurrentModificationException();
            for (; i < size && modCount == expectedModCount; i++)
                action.accept(elementAt(es, i));
            // update once at end to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }
    }

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

subList(int, int)

将指定区间 [fromIndex, toIndex) 的元素以列表的形式返回。

public List<E> subList(int fromIndex, int toIndex) {
    subListRangeCheck(fromIndex, toIndex, size); //检查索引是否合法
    return new SubList<>(this, fromIndex, toIndex);
}

forEach(Consumer<? super E>)

对列表中的每个元素执行给定的操作。

//例:
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
list.forEach(System.out::println); //即将list中的元素逐个输出
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();
}

spliterator()

在此集合中的元素上创建一个spliterator,用来遍历和划分集合元素。可用于并行遍历

public Spliterator<E> spliterator() {
    return new ArrayListSpliterator(0, -1, 0);
}

removeIf(Predicate<? super E>)

删除当前列表中满足给定条件的所有元素。

public boolean removeIf(Predicate<? super E> filter) {
    return removeIf(filter, 0, size);
}

removeIf(Predicate<? super E>, int, int)

删除当前列表中指定区间 [i, end) 中满足给定条件的所有元素。

遍历一次以查找要删除的元素,然后进行第二遍物理删除。

boolean removeIf(Predicate<? super E> filter, int i, final int end) {
    Objects.requireNonNull(filter);
    int expectedModCount = modCount;
    final Object[] es = elementData;
    // Optimize for initial run of survivors
    for (; i < end && !filter.test(elementAt(es, i)); i++)
        ;
    // Tolerate predicates that reentrantly access the collection for
    // read (but writers still get CME), so traverse once to find
    // elements to delete, a second pass to physically expunge.
    if (i < end) {
        final int beg = i;
        final long[] deathRow = nBits(end - beg);
        deathRow[0] = 1L;   // set bit 0
        for (i = beg + 1; i < end; i++)
            if (filter.test(elementAt(es, i)))
                setBit(deathRow, i - beg);
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        modCount++;
        int w = beg;
        for (i = beg; i < end; i++)
            if (isClear(deathRow, i - beg))
                es[w++] = es[i];
        shiftTailOverGap(es, w, end);
        return true;
    } else {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        return false;
    }
}

replaceAll(UnaryOperator<E>)

将当前列表中的每个元素替换为operator操作后的结果。

public void replaceAll(UnaryOperator<E> operator) {
    replaceAllRange(operator, 0, size);
    // TODO(8203662): remove increment of modCount from ...
    modCount++;
}
//例:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
list.replaceAll(i -> i + 1); //结果为:list = {2, 3, 4, 5, 6}

replaceAllRange(UnaryOperator<E>, int, int)

将当前列表 [i, end) 区间中的每个元素替换为operator操作后的结果。

private void replaceAllRange(UnaryOperator<E> operator, int i, int end) {
    Objects.requireNonNull(operator);
    final int expectedModCount = modCount;
    final Object[] es = elementData;
    for (; modCount == expectedModCount && i < end; i++)
        es[i] = operator.apply(elementAt(es, i));
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

sort(Comparator<? super E>)

按照给定的规则对当前列表进行排序,即使用指定的规则对 elementData 数组排序。

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

更多源码分析,请点击

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值