tags:

views:

690

answers:

7
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?

+19  A: 

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().

kd304
Indent it with four spaces and you don't have to escape <'s. I just did it for you.
Michael Myers
A: 

Because you're passing a null reference to println.

Edit: I sit corrected! An ArrayList is not an array.

Daniel Earwicker
Wonder which reference is null there?
kd304
-1 Not what's happening - and println will happily print "null" for a null reference
Michael Borgwardt
A: 

You've created empty array lists in the for loop, so trying access any element in them return null to System.out.println()

edit Sorry, wont' return null but instead throw ArrayIndexOutOfBoundsException.

Peter
+1  A: 

When you create a new ArrayList<Integer>(10), the "10" just indicates the initial capacity. It's still an empty list, and you can't call get(9) on it.

JacobM
+2  A: 

I believe that if you put

System.out.println(a.size());

after your first line, you'll see that the size of your outer array is zero. Thus the loop executes zero times, thus after the loop you are requesting the -1th element of a - and that's an error.

Carl Manaster
+1  A: 

a is an empty list so a.size() = 0 so in a.get(a.size()-1) the expression (a.size() - 1) is -1 so a.get(-1) throws ArrayIndexOutOfBoundsException

Gábor Hargitai
A: 

Note that new ArrayList(10) creates an empty ArrayList with its internal backing array initially set to size 10. The ArrayList is empty until you add elements to it. The constructor allows you specify the initial internal size as an optimization measure.

Steve Kuo