IndexOutOfBoundsException when adding to ArrayList at index

前端 未结 10 2150
既然无缘
既然无缘 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:52

    Your ArrayList is empty. With this line:

    s.add(1,"Elephant");
    

    You are trying to add "Elephant" at index 1 of the ArrayList (second position), which doesn't exist, so it throws a IndexOutOfBoundsException.

    Use

    s.add("Elephant");
    

    instead.

提交回复
热议问题