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 !
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With