Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 898
swing Avatar asked Nov 24 '14 19:11

swing


People also ask

How do you initialize an int ArrayList?

Here is a code example to show you how to initialize ArrayList at the time of declaration: ArrayList<Integer> numbers = new ArrayList<>(Arrays. asList(1, 2, 3, 4, 5, 6)); This is how you declare an ArrayList of Integer values.

How do you initialize an empty ArrayList in Java?

The general syntax of this method is:ArrayList<data_type> list_name = new ArrayList<>(); For Example, you can create a generic ArrayList of type String using the following statement. ArrayList<String> arraylist = new ArrayList<>(); This will create an empty ArrayList named 'arraylist' of type String.


1 Answers

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
like image 172
Jon Skeet Avatar answered Sep 19 '22 09:09

Jon Skeet