Java ArrayList add(index,element) 方法插入元素到数组指定位置
·
今天在开发项目的过程中,准备使用ArrayList 的 add(index,element) 来插入元素,天真的以为这样能给list排序
简略代码如下:
List list =
new ArrayList(50);list.add(0,element);list.add(2,element);list.add(1,element); |
|
编译运行之后抛出了exception,百思不得其解,等到看了源码之后才发现原因,ArrayList add(index,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++; } |
从代码中可以看出,当数组中的元素个数(size)小于index的时候,此方法是会抛出异常的。
所以此方法只适用于想要插入的位置小于数组中实际元素个数的时候才有作用。
也就是说,让list里面没有元素时,想通过插入元素到指定位置来达到排序的效果是不可行的。
更多推荐
所有评论(0)