IndexOutOfBoundsException when adding to ArrayList at index

前端 未结 10 2148
既然无缘
既然无缘 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 16:59

    You must add elements to ArrayList serially, starting from 0, 1 and so on.

    If you need to add elements to specific position you can do the following -

    String[] strings = new String[5];
    strings[1] = "Elephant";
    
    List s = Arrays.asList(strings);
    System.out.println(s); 
    

    This will produce the sollowing output

    [null, Elephant, null, null, null]
    

提交回复
热议问题