Java – why does this nested ArrayList code throw an exception?

ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>(5);
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 code snippet threw an exception in the print section Why?

Solution

You can only set the capacity of external / internal ArrayLists They are still empty

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));

Editor: Notice a.set (I,...) If I > = a.size (), an exception is thrown

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>