ArrayList集合底层是基于数组实现的,定义如下:
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
private transient Object[] elementData;
对集合数据的增删,就是对elementData数组的增删, add(E e)没什么好说的,说一下add(int index, E element)方法.
该方法在往ArrayList集合里添加数据的时候指定一个索引,但当这个索引上存在数据的时候怎么添加呢?
add(int index, E element)源码如下:
public void add(int index, E element) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
ensureCapacity(size+1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
所以如果在ArrayList集合中在已经存在数据的索引位置插入新数据,不会覆盖原数据,而是在该位置"挤一个空隙"插进去.
如有错误,欢迎指正.
end