Initialize ArrayList<ArrayList<Integer>>

I met a problem as follow:

When I initialize a ArrayList<ArrayList<Integer>>, the codes are:

ArrayList<ArrayList<Integer>> group = new ArrayList<ArrayList<Integer>>();
group.add((ArrayList<Integer>) Arrays.asList(1, 2, 3));
group.add((ArrayList<Integer>) Arrays.asList(4, 5, 6));
group.add((ArrayList<Integer>) Arrays.asList(7, 8, 9));
for (ArrayList<Integer> list : group) {
    for (Integer i : list) {
        System.out.print(i+" ");
    }
    System.out.println();
}

Although the codes can be compiled successfully, I still get a exception on console:

Exception in thread "main" java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList at Solution.main(Solution.java:49)

Thanks for help !

Jon Skeet
people
quotationmark

Arrays.asList doesn't return a java.util.ArrayList. It does return an instance of a class called ArrayList, coincidentally - but that's not java.util.ArrayList.

Unless you need this to really be an ArrayList<ArrayList<Integer>> I'd just change it to:

List<List<Integer>> group = new ArrayList<>();
group.add(Arrays.asList(1, 2, 3));
group.add(Arrays.asList(4, 5, 6));
group.add(Arrays.asList(7, 8, 9));
for (List<Integer> list : group) {
    ...
}

If you do need an ArrayList<ArrayList<...>> - or if you need to be able to add to the "inner" lists even if you don't need them with a static type of ArrayList - then you'll need to create a new ArrayList for each list:

group.add(new ArrayList<Integer>(Arrays.asList(1, 2, 3)));
// etc

people

See more on this question at Stackoverflow