今天在程序中写了这么段
List<FileNode> list=new ArrayList<FileNode>(10);
//System.out.println(list.get(1));
list.set(1, new FileNode());
两句都会出现异常
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
开始疑问指定大小 的这个参数起一个什么作用?
申请了固定大小的空间不能读 也不能写那指定大小又有什么作用呢?
List<FileNode> list=new ArrayList<FileNode>(10);
//System.out.println(list.get(1));
list.set(1, new FileNode());
两句都会出现异常
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
开始疑问指定大小 的这个参数起一个什么作用?
申请了固定大小的空间不能读 也不能写那指定大小又有什么作用呢?
直接通过add方法添加就行了。
List<FileNode> list=new ArrayList<FileNode>();
list.set(new FileNode());
Object element)Replaces the element at the specified position in this list with the specified element. Specified by:
set in interface List
Overrides:
set in class AbstractList
Parameters:
index - index of element to replace.
element - element to be stored at the specified position.
Returns:
the element previously at the specified position.
Throws:
IndexOutOfBoundsException - if index out of range (index < 0 || index >= size()).
以上是我从java arraylist api copy来的.
当 (index < 0 || index >= size()) 时会甩出 IndexOutOfBoundsException 因为你的list的size这是为零,所以就 Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
RangeCheck(index); E oldValue = elementData[index];
elementData[index] = element;
return oldValue;
}private void RangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
}