Bpache Bpache - 1 month ago 14
Java Question

[Ljava.lang.Object; cannot be cast to [Ljava.util.ArrayList;

In my java code, I try to build a list of arraylist, my code is as follows,

private ArrayList<Integer>[] listoflist;
listoflist = (ArrayList<Integer>[]) new Object[875715];


However, when I compile the code, the compiler keeps saying that



[Ljava.lang.Object; cannot be cast to [Ljava.util.ArrayList;



Can I ask why I can not cast Object[] to ArrayList[]?

Answer

You said that you're trying to build a list of ArrayLists. But... you're trying to use an array to do that... Why not just use another ArrayList? It's actually pretty easy:

private List<List<Integer>> listoflist = new ArrayList<ArrayList<Integer>>();

Here's an example of using it:

ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(Integer.valueOf(3));
list1.add(Integer.valueOf(4));
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(Integer.valueOf(6));
list2.add(Integer.valueOf(7));
listoflist.add(list1);
listoflist.add(list2);

Saying ArrayList<ArrayList<Integer>> so many times is kinda weird, so in Java 7 the construction can just be new ArrayList<>(); (it infers the type from the variable you're assigning it to).