IndexOutOfBoundsException when adding to ArrayList at index

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

    add(int index, E element) API says, Your array list has zero size, and you are adding an element to 1st index

    Throws:

    IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())
    

    Use boolean add(E e) instead.

    UPDATE based on the question update

    I can make it work, but I am trying to understand the concepts, so I changed declaration to below but didnt work either.

    ArrayList s = new ArrayList<>(10)
    

    When you call new ArrayList(10), you are setting the list's initial capacity to 10, not its size. In other words, when constructed in this manner, the array list starts its life empty.

提交回复
热议问题