标签:syn row 作业 适用于 nts public ++ cep 异常
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里面没有元素时,想通过插入元素到指定位置来达到排序的效果是不可行的。
标签:syn row 作业 适用于 nts public ++ cep 异常
原文地址:http://www.cnblogs.com/mzybuaa/p/7214466.html