more casting fun!

jbm's icon

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...

This:

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

Thoughts?

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.

J.

-------------------

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!

cheers.

nick rothwell | project cassiel's icon

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://
www.cassiel.com