Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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[]?

like image 694
Bpache Avatar asked Mar 09 '13 19:03

Bpache


2 Answers

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

like image 63
Riking Avatar answered Oct 07 '22 01:10

Riking


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));
like image 41
michael_s Avatar answered Oct 06 '22 23:10

michael_s