Re: Cast to multidimensional arrays
From: BarryNL (barry_at_nospam.nl)
Date: 01/30/04
- Next message: Yoyoma_2: "Re: Mars Rover Not Responding"
- Previous message: Adam Jenkins: "Re: What do you think about JDO?"
- In reply to: Jay: "Cast to multidimensional arrays"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Fri, 30 Jan 2004 17:27:54 +0100
Jay wrote:
> 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][]);
- Next message: Yoyoma_2: "Re: Mars Rover Not Responding"
- Previous message: Adam Jenkins: "Re: What do you think about JDO?"
- In reply to: Jay: "Cast to multidimensional arrays"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|