Re: Cast to multidimensional arrays

From: BarryNL (barry_at_nospam.nl)
Date: 01/30/04


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][]);



Relevant Pages

  • Re: Search all the characters then get range for some of them
    ... OK, Jay and Doug, I mis-understood your solutions. ... to know the positions of each word in a document so we can gray it out later ... array, but loading an array with the list of words that you need to search ... Dim WordsToFind As Variant ...
    (microsoft.public.word.vba.general)
  • Re: Search all the characters then get range for some of them
    ... It's a simple matter to load the words into an array and then use code ... "Jay Freedman" wrote: ... characters and/or their formatting, you can do that by specifying the ... Dim oRg As Range ...
    (microsoft.public.word.vba.general)
  • Re: vector --> array
    ... With its toArray() method. ... First, the toArray() method returns an Objectarray, ... this to a String[] array. ... you can use the iterator() method to get ...
    (comp.lang.java.help)
  • Re: vector --> array
    ... With its toArray() method. ... First, the toArray() method returns an Objectarray, ... this to a String[] array. ... you can use the iterator() method to get ...
    (comp.lang.java.help)
  • Re: Hours
    ... Thanks Jay ... However, and forgive me if this is wrong, I set up an array of an ListArray ... Geoff ...
    (microsoft.public.dotnet.languages.csharp)