Why does this nested ArrayList code throw an exception?

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 print part. Why?

+3
source share
6 answers

You only set the capacity of the external / internal ArrayLists. They are still empty.
And your loop is not even executed, because it a.size()is 0.
You will 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 follow up a.set(i, ...). It throws an exception if I> = a.size ().

+19
source

I believe that if you put

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

, . , , -1- a - .

+2

new ArrayList<Integer>(10), "10" . , get(9).

+1

a - , a.size() = 0, a.get(a.size() - 1) (a.size() - 1) -1, a.get(- 1) ArrayIndexOutOfBoundsException

+1

for, , , null System.out.println()

, wont ' null, ArrayIndexOutOfBoundsException.

0

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

0
source

Source: https://habr.com/ru/post/1711023/


All Articles