[kepler-dev] java question: array casts

Tobin Fricke tobin at splorg.org
Mon Aug 16 15:50:55 PDT 2004


I am building up a List of tokens that I eventually want to turn into an
ArrayToken.  I am using the intermediate List because I do not know the
final array length a priori.

 List resultList = new LinkedList();
 Token t = ...
 resultList.add(t);

Now I want to turn this List of tokens into an ArrayToken.  The method
resultList.toArray() will return an Object[] array containing exactly the
items in the list.  Now I want to call the ArrayToken(Token[])
constructor.  I thought I might be able to cast Object[] to Token[] and
Java might distribute the cast across the array:

 return new ArrayToken((Token[])(resultList.toArray()));

But that generates a ClassCastException (because it's true that the
resultList.toArray() has type Object[] and not Token[], although it
contains only Tokens).

As a kludge, I can copy the contents of result into a new array of the
proper type, although it's rather ridiculous to create a copy just to
satisfy the typechecking:

  Token[] resultArray = new Token[resultList.size()];
  System.arraycopy(resultList.toArray(), 0, resultArray, 0,
                   resultList.size());
  return new ArrayToken(resultArray);

Here's some stand-alone code to demonstrate the effect:

import java.util.List;
import java.util.LinkedList;

public class ArrayCastExperiment {
    public static void main(String arg[]) {
        List foo = new LinkedList();
        foo.add("This is a test");
        String bar[] = (String[])(foo.toArray()); // CastCastException!
        System.out.println(bar[0]);
    }
}

What's the right way to do this?

Tobin



More information about the Kepler-dev mailing list