Why does this nested ArrayList code throw an exception?

arraylist, java

Solution

You set only the capacity of the outer/inner ArrayLists. They are still empty. And your loop doesn't even execute because `a.size()` is 0. You need a second inner loop to add elements to them.

ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>(5);
for (int i = 0; i < 5 ; i++) {
    List<Integer> lst = new ArrayList<Integer>(10);
    for (int j = 0; j < 10; j++) {
        lst.add(j);
    }   
    a.add(lst);
}
System.out.println(a.get(a.size()-1).get(9));

Edit: And watch out for `a.set(i, ...)`. It throws exception if i >= a.size().

Problem

``` ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>(5); for (int i = 0 ; i < a.size() ; i++){ a.set(i, new ArrayList<Integer>(10)); } System.out.println(a.get(a.size()-1).get(9)); //exception thrown ``` The above snippet throws an exception in the printing part. Why?

Original source