[kepler-dev] java question: array casts
xiaowen
xin2 at llnl.gov
Mon Aug 16 16:11:32 PDT 2004
Hi Tobin,
Perhaps you could try:
import java.util.List;
import java.util.LinkedList;
public class Test {
public static void main(String arg[]) {
List foo = new LinkedList();
foo.add("This is a test");
String bar[] = (String[])(foo.toArray(new String[foo.size()]));
System.out.println(bar[0]);
}
}
Xiaowen
On Aug 16, 2004, at 3:50 PM, Tobin Fricke wrote:
> 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
> _______________________________________________
> kepler-dev mailing list
> kepler-dev at ecoinformatics.org
> http://www.ecoinformatics.org/mailman/listinfo/kepler-dev
More information about the Kepler-dev
mailing list