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>();
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).
Java is a strong typed language - hence you cannot simply cast one type to the other. However you can convert them.
In case of Object[]
to List
simply use
Object[] arr = new Object[]{...};
List<Object> list = Arrays.asList(arr);
and if you want to use it as an ArrayList
, e.g. if you want to add some other elements, simply wrap it again
ArrayList<Object> arrList = new ArrayList<Object>(Arrays.asList(arr));
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