ArrayList小计

103 阅读2分钟

int DEFAULT_CAPACITY = 10:默认空间大小10

Object[] EMPTY_ELEMENTDATA = {}:初始化容量为0时使用

Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}:初始化容量默认时使用

transient Object[] elementData:元素数组,初始化不为0时new Object[n]

 传入Collection的构造函数

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():修剪多余的空间,调用Arrays.copyOf()方法
public void trimToSize() {
    modCount++;
    if (size < elementData.length) {
        elementData = (size == 0)
          ? EMPTY_ELEMENTDATA
          : Arrays.copyOf(elementData, size);
    }
}
add(E e):尾插,返回true
public boolean add(E e) {
    //当前数组长度+1进行判断,如果-数组长度小于0.调用grow扩容
    ensureCapacityInternal(size + 1);
    elementData[size++] = e;
    return true;
}
grow(int minCapacity):扩容方法,调用Arrays.copyOf()
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);//扩容为1.5
    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);
}
Arrays.copyOf():Arrays工具包的复制数据方法,调用native方法System.arraycopy()
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;
}
add(int index, E element):元素插入到索引位置,调用System.arraycopy()复制自己,把插入后置及以后的元素后移一位(索引加一)
public void add(int index, E element) {
    rangeCheckForAdd(index);//检查index是否越界
​
    ensureCapacityInternal(size + 1);  //判断是否需要grow扩容
    System.arraycopy(elementData, index, elementData, index + 1,size - index);
    elementData[index] = element;
    size++;
}
remove(int index):删除指定索引处元素,并返回该元素。调用System.arraycopy()使后续元素索引-1
public E remove(int index) {
    rangeCheck(index);
    modCount++;
    E oldValue = elementData(index);//获取该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):调用fastRemove()删除指定的元素,返回true。没有该元素返回false
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(int index):删除指定元素时掉用的方法,仍是调用System.arraycopy()方法
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():清空list,把size置为0
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<? extends E> c):把集合中的元素添加到list尾部,返回true。目标集合长度为0时返回false。仍是调用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):在指定index索引位置添加目标集合中的元素,同上
removeRange(int fromIndex, int toIndex):移除[m,n)区间的元素,左闭右开
removeAll(Collection<?> c):从list移除目标集合中的元素。调用batchRemove批量删除方法
public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, false);
}
batchRemove(Collection<?> c, boolean complement):
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++)
            //complement,false代表不在目标集合中时,备份到数组前面
            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;
        }
        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;
}
listIterator(int index):返回索引位置开始的正确顺序迭代器,无参重载listIterator()默认为0
private class ListItr extends Itr implements ListIterator<E>
iterator():返回一个Itr迭代器
private class Itr implements Iterator<E>
subList(int fromIndex, int toIndex):返回索引区间的一个“视图”,SubList是ArrayList的内部类
private class SubList extends AbstractList<E> implements RandomAccess
sort(Comparator<? super E> c):排序,调用Arrays.sort()
@Override
@SuppressWarnings("unchecked")
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++;
}
removeIf(Predicate<? super E> filter):删除list中满足filter过滤条件的元素
replaceAll(UnaryOperator operator):对所有元素统一操作