今天在程序中写了这么段
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
开始疑问指定大小 的这个参数起一个什么作用?
申请了固定大小的空间不能读 也不能写那指定大小又有什么作用呢?

解决方案 »

  1.   

    按顺序先存0而且最好用list.add( new FileNode());
      

  2.   

    首先arraylist是动态数组,没有必要指定大小,
    直接通过add方法添加就行了。
    List<FileNode> list=new ArrayList<FileNode>();
    list.set(new FileNode());
      

  3.   

    public Object set(int index,
                      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 
      

  4.   

    两段代码, 应该能看明白public E set(int index, E element) {
    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);
    }
      

  5.   

    为什么要有new ArrayList<FileNode>(10);这个构造方法?既然指定大小 没有什么用处为什么还要有这么一个指定大小 的构造方法呢,它有什么用呢?与new ArrayList<FileNode>();有什么不同?
      

  6.   

    回楼上,当你确定了ArrayList的容量时,可以指定初始的容量.这样可以避免代码运行时系统对ArrayList容量的变更,效率也就高一点点。new ArrayList <FileNode>(10)与new ArrayList <FileNode>()是完全相同的,因为你不指定ArrayList的初始容量时,系统自动设为10。