0

The following snippet throws an Exception in printin part....

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

can anyone explain why...

thanks in advance...

3
Contributors
2
Replies
4
Views
8 Years
Discussion Span
Last Post by yilmazhuseyin
0

there's nothing in the value/its not initialized. I don't think you have to initialize the arraylists inside the first one, they're already there. You just have to initialize the numbers inside. ;D

0

you have nested array lists here (as you know. )

ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>(5);
/*create a new arraylists of arraylist so outer arraylist has 5 element which means size of a=5*/
        for(int i = 0 ; i < a.size() ; i++){
            a.set(i, new ArrayList<Integer>(10));
/*loop over 5 elements of a and put an arraylist of 10 integers in the lists.*/
        }
/*at this point you got object named a (arraylist of arraylists of Integer objects) but you haven't put any integer in inner arraylist. so a.get(4).get(9) is not assigned yet.*/ 
        System.out.println(a.get(a.size()-1).get(9));//exception thrown
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.