ArrayList中四种add方法简介说明
下文简述Arraylist源码中的四种add方法,如下所示
ArrayList之add方法源码分析
四种add方法分别为:
末尾添加元素
指定位置添加元素
一次添加多个元素(添加集合)
在指定位置上添加集合
例:ArrayList之add方法源码分析
//添加一个特定的元素到list的末尾
public boolean add(E e) {
//先确保elementData数组的长度足够,size是数组中数据的个数,
//由于只添加一个元素,所以size+1
//先判断size+1的这个个数数组能否放得下,在这个方法中去判断数组长度是否够用
ensureCapacityInternal(size + 1); // Increments modCount!!
//在数据中正确的位置上放上元素e,并且size++
elementData[size++] = e;
return true;
}
//在指定位置添加一个元素
public void add(int index, E element) {
rangeCheckForAdd(index);
//先确保elementData数组的长度足够
ensureCapacityInternal(size + 1); // Increments modCount!!
//将数据整体向后移动一位,空出位置之后再插入,效率不太好
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
// 校验插入位置是否合理
private void rangeCheckForAdd(int index) {
//插入的位置肯定不能大于size 和小于0
if (index > size || index < 0)
//如果是,就报越界异常
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
//添加一个集合
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;
//新数组有元素,就返回 true
return numNew != 0;
}
//在指定位置,添加一个集合
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;
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


