简体   繁体   English

为什么这个嵌套的ArrayList代码抛出异常?

[英]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. 您只设置外部/内部ArrayLists的容量。 They are still empty. 他们仍然是空的。
And your loop doesn't even execute because a.size() is 0. 并且您的循环甚至不执行,因为a.size()为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, ...) . 编辑:注意a.set(i, ...) It throws exception if i >= a.size(). 如果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. 因此循环执行零次,因此在循环之后,您正在请求a的第-1个元素 - 这是一个错误。

When you create a new ArrayList<Integer>(10) , the "10" just indicates the initial capacity. 创建new ArrayList<Integer>(10) ,“10”只表示初始容量。 It's still an empty list, and you can't call get(9) on it. 它仍然是一个空列表,你不能在它上面调用get(9)

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() 您已在for循环中创建了空数组列表,因此尝试访问其中的任何元素都会返回null到System.out.println()

edit Sorry, wont' return null but instead throw ArrayIndexOutOfBoundsException. 编辑抱歉,不会返回null,而是抛出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. 请注意, new ArrayList(10)创建一个空的 ArrayList,其内部支持数组最初设置为10。在向元素添加元素之前,ArrayList为空。 The constructor allows you specify the initial internal size as an optimization measure. 构造函数允许您将初始内部大小指定为优化度量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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