Cast to multidimensional arrays

J

Jay

Why does the following code produce a ClassCastException?

ArrayList list = new ArrayList();
list.add(new Object[]{"Test1", "..."});
list.add(new Object[]{"Test2", "..."});
list.add(new Object[]{"Test3", "..."});

Object ar[][] = (Object[][]) list.toArray();


The last line causes a ClassCastException... Yet, list.toArray() is
just an array of objects which are themselves arrays of objects. So
list.toArray is an Object[][], conceptually. Why does Java complain?
 
B

BarryNL

Jay said:
Why does the following code produce a ClassCastException?

ArrayList list = new ArrayList();
list.add(new Object[]{"Test1", "..."});
list.add(new Object[]{"Test2", "..."});
list.add(new Object[]{"Test3", "..."});

Object ar[][] = (Object[][]) list.toArray();


The last line causes a ClassCastException... Yet, list.toArray() is
just an array of objects which are themselves arrays of objects. So
list.toArray is an Object[][], conceptually. Why does Java complain?

Because the toArray() method is returning an Object[] and the contents
of each array item just happens to be an Object[]. Consider that this
*is OK*, if used above:

Object ar[] = list.toArray();
ar[0] = "A String"; // No longer an Object[]

what you need to do is force the correct return type with:

Object ar[][] = (Object[][]) list.toArray(new Object[0][]);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top