ArrayList

ArrayList

继承AbstractList,实现了List, RandomAccess, Cloneable, java.io.Serializable接口

成员变量

1、private static final int DEFAULT_CAPACITY = 10;

初始容量为10

2、private static final Object[] EMPTY_ELEMENTDATA = {};

构造函数赋初始大小为0时引用这个数组

3、private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

调用无参构造函数时引用这个数组

4、transient Object[] elementData;

存储ArrayList的元素的数组缓冲区。 ArrayList的容量是该数组缓冲区的长度。

5、private int size;

包含的元素数量

6、protected transient int modCount = 0;

记录操作数

7、private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

设置数组长度最大为Integer.MAX_VALUE - 8

构造函数

1、

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

赋值初始大小

2、

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

3、

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

使用其他集合元素创建,先将集合c转换为数组,如果c不包含元素,则elementData设置为EMPTY_ELEMENTDATA,否则调用Arrays.copyOf赋值

c.toArray might (incorrectly) not return Object[]?

如果集合c重写了toArray返回的不是Object数组,数组元素是Object的子类,对数组中的元素赋Object类型的值就会出现下转型异常

方法

1、public void trimToSize()

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

增加操作次数,使用Arrays.copyOf创建新数组,将数组缓冲区调整至size大小,节省内存占用,说明实际ArrayList实际存储元素和缓冲数组的长度并不一定保持一致

2、public void ensureCapacity(int minCapacity)

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

确定容量,如果缓冲数组不为空数组,最小花费为0,否则为默认值10,如果传入的最小容量比最小花费大,调用ensureExplicitCapacity

3、private static int calculateCapacity(Object[] elementData, int minCapacity)

private static int calculateCapacity(Object[] elementData, int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    return minCapacity;
}

4、private void ensureCapacityInternal(int minCapacity)

    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

add时调用,如果数组是默认的空数组,在10和传入参数中选取最大值进行再次确认容量

5、private void ensureExplicitCapacity(int minCapacity)

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

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

再次确认容量,操作数增加,如果缓冲数组的长度不满足,则调用grow

6、private void grow(int minCapacity)

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

扩容,计算新的容量大小,先设置为原先的150%,如果还是不够则设置为传入的容量大小,如果大于最大容量,则调用hugeCapacity计算,最后使用Arrays.copyOf创建新数组

7、private static int hugeCapacity(int minCapacity)

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

针对大容量,如果传入容量为负数,说明溢出,抛出异常,如果传入容量大于Integer.MAX_VALUE-8,返回Integer.MAX_VALUE,否则返回Integer.MAX_VALUE-8

8、public int size()

public int size() {
    return size;
}

返回大小

9、public boolean isEmpty()

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

将size与0比较

10、public boolean contains(Object o)

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

寻找o的下标,如果不为-1,返回true

11、public int indexOf(Object o)

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

for循环遍历比较,返回下标,没找到返回-1

12、public int lastIndexOf(Object o)

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

for循环逆向遍历比较,返回下标,没找到返回-1

13、public 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);
    }
}

返回实例的浅拷贝,即new了新的对象,但新对象引用型成员变量指向原对象引用型成员变量的地址,在这里使用Arrays.copyOf给了新的数组,并且操作数记为0

14、public Object[] toArray()

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

使用Arrays.copyOf返回和缓冲区数组一样的新数组

15、public T[] 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;
}

如果数组a大小不满足,使用Arrays.copyOf返回,否则使用System.arraycopy填充,多余的置为null

16、E elementData(int index)

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

返回指定下标处的元素

17、public E get(int index)

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

    return elementData(index);
}

先确定是否越界,再调用elementData返回

18、public E set(int index, E element)

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

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

先确定是否越界,再设置新值,返回旧值

19、public boolean add(E e)

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

先确认内部容量,再在末尾加入新元素

20、public void add(int index, E element)

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

    ensureCapacityInternal(size + 1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,
                     size - index);
    elementData[index] = element;
    size++;
}

先确认是否越界,在确认内部容量,从index后的元素后移,在指定位置添加元素

21、public E remove(int index)

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

先判断数组是否越界,增加操作数,将指定下标后的元素前移,最后一个元素置为null,size-1,让gc回收多余空间,返回被删除的元素

22、private void fastRemove(int index)

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
}

不检查越界也不返回被删除的元素,操作数+1

23、public void clear()

public void clear() {
    modCount++;

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

    size = 0;
}

操作数+1,数组元素置为null,size置为0

24、public boolean addAll(Collection<? extends E> c)

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

集合c转为数组,确认容量是否足够,再用System.arraycopy向后填充自身,size增加c集合元素个数

25、public boolean addAll(int index, Collection<? extends E> c)

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

在指定下标处加入c中的元素,需要确认下标是否越界,确认元素是否需要后移,也会增加操作数。

26、protected void removeRange(int fromIndex, int toIndex)

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

删除范围内的元素,增加操作数

27、private void rangeCheck(int index)

private void rangeCheck(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

判断是否越界

28、private void rangeCheckForAdd(int index)

private void rangeCheckForAdd(int index) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

添加时判断是否越界,增加了对负数的判断

29、private String outOfBoundsMsg(int index)

private String outOfBoundsMsg(int index) {
    return "Index: "+index+", Size: "+size;
}

返回越界时数组大小和错误的下标

30、public boolean removeAll(Collection<?> c)

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

先判断c是否为空,然后调用batchRemove进行删除

31、public boolean retainAll(Collection<?> c)

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

先判断c是否为空,然后调用batchRemove进行删除

32、private boolean 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++)
            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;
}

将符合要求的元素移动到数组前边,后边元素置为null,调整大小,增加对应的操作数

33、private void writeObject(java.io.ObjectOutputStream s)

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

序列化写出,写出集合大小和集合内元素,会比较值操作数

34、 private void readObject(java.io.ObjectInputStream s)

private void readObject(java.io.ObjectInputStream s)
    throws java.io.IOException, ClassNotFoundException {
    elementData = EMPTY_ELEMENTDATA;

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

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

    if (size > 0) {
        // be like clone(), allocate array based upon size not capacity
        int capacity = calculateCapacity(elementData, size);
        SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity);
        ensureCapacityInternal(size);

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

序列化读入,建立一个新的数组,只读取size个元素。

35、public ListIterator listIterator(int index)

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

返回一个指定位置的listIterator,先判断下标是否越界

36、public ListIterator listIterator()

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

返回位于起始位置的ListIterator

37、public Iterator iterator()

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

返回一个Iterator

38、public List subList(int fromIndex, int toIndex)

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

先检查需求的子数组范围是否正确,再返回子数组

39、static void subListRangeCheck(int fromIndex, int toIndex, int size)

static void subListRangeCheck(int fromIndex, int toIndex, int size) {
    if (fromIndex < 0)
        throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
    if (toIndex > size)
        throw new IndexOutOfBoundsException("toIndex = " + toIndex);
    if (fromIndex > toIndex)
        throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                           ") > toIndex(" + toIndex + ")");
}

判断是否越界以及起始下标是否比结尾下标大

40、public void forEach(Consumer<? super E> action)

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

判断action是否为空,接着对集合内所有元素进行操作,每一次操作前都会比较操作数

41、public Spliterator spliterator()

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

42、public boolean removeIf(Predicate<? super E> filter)

@Override
public boolean removeIf(Predicate<? super E> filter) {
    Objects.requireNonNull(filter);
    // figure out which elements are to be removed
    // any exception thrown from the filter predicate at this stage
    // will leave the collection unmodified
    int removeCount = 0;
    final BitSet removeSet = new BitSet(size);
    final int expectedModCount = modCount;
    final int size = this.size;
    for (int i=0; modCount == expectedModCount && i < size; i++) {
        @SuppressWarnings("unchecked")
        final E element = (E) elementData[i];
        if (filter.test(element)) {
            removeSet.set(i);
            removeCount++;
        }
    }
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }

    // shift surviving elements left over the spaces left by removed elements
    final boolean anyToRemove = removeCount > 0;
    if (anyToRemove) {
        final int newSize = size - removeCount;
        for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
            i = removeSet.nextClearBit(i);
            elementData[j] = elementData[i];
        }
        for (int k=newSize; k < size; k++) {
            elementData[k] = null;  // Let gc do its work
        }
        this.size = newSize;
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

    return anyToRemove;
}

使用BitSet存储符合过滤器的元素的数组下标并记录要删除元素的个数,将数组中不删除的元素放到前边,后面置为null,最终操作数+1

43、public void replaceAll(UnaryOperator operator)

@Override
@SuppressWarnings("unchecked")
public void replaceAll(UnaryOperator<E> operator) {
    Objects.requireNonNull(operator);
    final int expectedModCount = modCount;
    final int size = this.size;
    for (int i=0; modCount == expectedModCount && i < size; i++) {
        elementData[i] = operator.apply((E) elementData[i]);
    }
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    modCount++;
}

将数组中的每一个元素改为lambda表达式返回的结果,会判断操作数,最终操作数+1

44、public void sort(Comparator<? super E> c)

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

使用指定比较器,调用Arrays.sort进行排序,会判断操作数,最终操作数+1

内部类

ArrayListSpliterator
Itr
Listltr
SubList

与AbstractList思路类似,暂时放着,以后填坑

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值