Forums > Java

more casting fun!

Nov 22 2006 | 4:36 pm

Okay, I’m crap at solving casting problems… I try, but…

I’ve got an ArrayList that I’m trying to convert to an Atom[] using the .toArray() provided by ArrayList. Seems simple enough, but…


Atom[] stuff = theList.toArray();

fails to compile (needs Atom[], finds Object[]) No problem.

so, this:

Atom[] stuff = (Atom[])theList.toArray();

compiles, but fails with a ClassCastException in at runtime


I know what’s going on, but I can’t get the syntax. The "theList" is being created as ArrayList, so I don’t get what’s up.



Ha! Found it, but I’ll post all this anyway, for any other unfortunate souls stumbling into similar confusion:

Atom[] stuff = theList.toArray(new Atom[theList.size()]);

That works!


Nov 22 2006 | 4:46 pm

On 22 Nov 2006, at 16:36, jbmaxwell wrote:

> Atom[] stuff = theList.toArray();

ArrayList needs a template array to determine the type: so

Atom[] stuff = theList.toArray(new Atom[] { });

nick rothwell — composition, systems, performance — http://

Viewing 2 posts - 1 through 2 (of 2 total)

Forums > Java