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
上面的代码片段在打印部分引发了异常。为什么?
您只设置外部/内部 ArrayLists 的容量。他们仍然是空的。
而且你的循环甚至没有执行,因为a.size()
它是 0。
你需要第二个内部循环来向它们添加元素。
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));
编辑:并注意a.set(i, ...)
. 如果 i >= a.size() 则抛出异常。
我相信如果你把
System.out.println(a.size());
在第一行之后,您会看到外部数组的大小为零。因此循环执行零次,因此在循环之后您请求 a - 的第 -1 个元素,这是一个错误。
a 是一个空列表,所以 a.size() = 0 所以在 a.get(a.size()-1) 表达式 (a.size() - 1) 是 -1 所以 a.get(-1) 抛出ArrayIndexOutOfBoundsException
创建时new ArrayList<Integer>(10)
,“10”仅表示初始容量。它仍然是一个空列表,你不能调用get(9)
它。
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.
您已经在 for 循环中创建了空数组列表,因此尝试访问其中的任何元素都会将 null 返回给 System.out.println()
编辑 对不起,不会'返回 null 而是抛出 ArrayIndexOutOfBoundsException。