Initialize ArrayList <ArrayList <Integer>>

I met the problem as follows:

When I initialize 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 an exception on the console:

An exception in the main thread java.lang.ClassCastException: java.util.Arrays $ ArrayList cannot be thrown in java.util.ArrayList in Solution.main (Solution.java:49)

Thanks for the help!

+6
source share
4 answers

Arrays.asList does not return java.util.ArrayList . It returns an instance of a class called ArrayList , by coincidence, but it is not java.util.ArrayList .

If you don't need it to really be an ArrayList<ArrayList<Integer>> , I would 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 need an ArrayList<ArrayList<...>> - or if you need to add to the internal lists, even if you do not need them with the static type ArrayList - then you will need to create a new ArrayList for each list:

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

The return of Arrays.asList not java.util.ArrayList ; java.util.Arrays$ArrayList is a separate class nested in Arrays , even if it is a List .

If you must have an ArrayList , then create another ArrayList yourself, using the returned List from Arrays.asList instead of casting, for example:

 group.add(new ArrayList<Integer>( Arrays.asList(1, 2, 3) )); 
+4
source

Arrays.asList returns an instance of the nested static type java.util.Arrays.ArrayList , which is different from java.util.ArrayList . You can avoid this problem by programming the List interface (which is also implemented by java.util.Arrays.ArrayList ) and without unnecessary 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(); } 
+2
source
 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 read this code. This can help you achieve your requirements.

0
source

Source: https://habr.com/ru/post/978641/


All Articles