简体   繁体   中英

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

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

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.

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.

a是一个空列表,所以a.size()= 0所以在a.get(a.size() - 1)中表达式(a.size() - 1)是-1所以a.get(-1)抛出ArrayIndexOutOfBoundsException异常

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM