备战Java面试[JDK集合源码系列] -- ArrayList源码解析,计算机程序设计员证书

  • @param element 要插入的元素

  • @throws IndexOutOfBoundsException {@inheritDoc}

*/

public void add(int index, E element) {

// 检查是否越界

rangeCheckForAdd(index);

// 检查是否需要扩容

ensureCapacityInternal(size + 1); // Increments modCount!!

// 将inex及其之后的元素往后挪一位,则index位置处就空出来了

// 进行了size-索引index次操作

System.arraycopy(elementData, index, elementData, index + 1,

size - index);

// 将元素插入到index的位置

elementData[index] = element;

// 元素数量增1

size++;

}

/**

  • A version of rangeCheck used by add and addAll.

  • add和addAll方法使用的rangeCheck版本

*/

// 检查是否越界

private void rangeCheckForAdd(int index) {

if (index > size || index < 0)

throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

}

复制代码

执行流程:

  • 检查索引是否越界;

  • 检查是否需要扩容;

  • 把插入索引位置后的元素都往后挪一位;

  • 在插入索引位置放置插入的元素;

  • 元素数量增1;

**3.addAll(Collection c)添加所有集合参数中的所有元素

求两个集合的并集:**

/**

  • Appends all of the elements in the specified collection to the end of

  • this list, in the order that they are returned by the

  • specified collection’s Iterator. The behavior of this operation is

  • undefined if the specified collection is modified while the operation

  • is in progress. (This implies that the behavior of this call is

  • undefined if the specified collection is this list, and this

  • list is nonempty.)

  • 将集合c中所有元素添加到当前ArrayList中

    • @param c collection containing elements to be added to this list
  • @return true if this list changed as a result of the call

  • @throws NullPointerException if the specified collection is null

*/

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

// 将集合c转为数组

Object[] a = c.toArray();

int numNew = a.length;

// 检查是否需要扩容

ensureCapacityInternal(size + numNew); // Increments modCount

// 将c中元素全部拷贝到数组的最后

System.arraycopy(a, 0, elementData, size, numNew);

// 集合中元素的大小增加c的大小

size += numNew;

// 如果c不为空就返回true,否则返回false

return numNew != 0;

}

复制代码

执行流程:

  • 拷贝c中的元素到数组a中;

  • 检查是否需要扩容;

  • 把数组a中的元素拷贝到elementData的尾部;

访问操作

**4.get(int index)获取指定索引位置的元素

获取指定索引位置的元素,时间复杂度为O(1)。**

/**

  • Returns the element at the specified position in this list.

    • @param index index of the element to return
  • @return the element at the specified position in this list

  • @throws IndexOutOfBoundsException {@inheritDoc}

*/

public E get(int index) {

// 检查是否越界

rangeCheck(index);

// 返回数组index位置的元素

return elementData(index);

}

/**

  • Checks if the given index is in range. If not, throws an appropriate

  • runtime exception. This method does not check if the index is

  • negative: It is always used immediately prior to an array access,

  • which throws an ArrayIndexOutOfBoundsException if index is negative.

  • 检查给定的索引是否在集合有效元素数量范围内

  • <
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值