IndexOutOfBoundsException when adding to ArrayList at index

前端 未结 10 2149
既然无缘
既然无缘 2020-12-17 16:39

I get exception Exception in thread \"main\" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0 for the below code. But couldn\'t understand why.

         


        
10条回答
  •  粉色の甜心
    2020-12-17 17:05

    You can initialize the size (not the capacity) of an ArrayList in this way:

    ArrayList list = new ArrayList(Arrays.asList(new T[size]));
    

    in your case:

    ArrayList s = new ArrayList(Arrays.asList(new String[10]));
    

    this creates an ArrayList with 10 null elements, so you can add elements in random order within the size (index 0-9).

提交回复
热议问题