Bpache Bpache - 7 months ago 77
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[]?


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>();
ArrayList<Integer> list2 = new ArrayList<Integer>();

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).