IndexOutOfBoundsException when adding to ArrayList at index

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

    If you REALLY want "Elephant" at index 1, then you can add another (e.g. null) entry at index 0.

    public class App {
    public static void main(String[] args) {
        ArrayList s = new ArrayList<>();
    
        s.add(null);
        s.add("Elephant");
    
        System.out.println(s.size());                
      }
    }
    

    Or change the calls to .add to specify null at index 0 and elephant at index 1.

提交回复
热议问题