Reputation: 159
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 !
Upvotes: 9
Views: 24072
Reputation: 19
group.add(new ArrayList<Integer>((Arrays.asList(1, 2, 3))));
group.add(new ArrayList<Integer>((Arrays.asList(4, 5, 6))));
group.add(new ArrayList<Integer>((Arrays.asList(7, 8, 9))));
for (ArrayList<Integer> arrayList : group) {
for (Integer integer : arrayList) {
System.out.println(integer);
}
}
Please refer this code. This might help you out to achieve your requirement.
Upvotes: 1
Reputation: 1502935
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
Upvotes: 12
Reputation: 72884
Arrays.asList
returns an instance of a nested static type java.util.Arrays.ArrayList
that is different from java.util.ArrayList
. You can avoid this problem by programming to the List
interface (which java.util.Arrays.ArrayList
implements as well) and without the unneeded casts:
List<List<Integer>> group = new ArrayList<List<Integer>>();
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) {
for (Integer i : list) {
System.out.print(i+" ");
}
System.out.println();
}
Upvotes: 4
Reputation: 178303
The return of Arrays.asList
is not a java.util.ArrayList
; the java.util.Arrays$ArrayList
is a separate class, nested in Arrays
, even if it's a List
.
If you must have an ArrayList
, then create another ArrayList
yourself using the returned List
from Arrays.asList
, instead of casting, e.g.:
group.add(new ArrayList<Integer>( Arrays.asList(1, 2, 3) ));
Upvotes: 5