Re: Yet Another ClassCastException Question
"Michael Powe" <michael+gnus@trollope.org> wrote in message
news:87odyif54u.fsf@ellen.trollope.org...
"Mike" == Mike Schilling <mscottschilling@hotmail.com> writes:
Mike> "Michael Powe" <michael+gnus@trollope.org> wrote in message
Mike> news:ulktmjud6.fsf@trollope.org...
>> The cast to sortedEntryDates throws a ClassCastException when
>> the method is invoked on an ArrayList of Date objects.
>> Why? I have another, clunky way of getting the dates into the
>> array, using System.arraycopy(), but I'd like to know why this
>> way does not work.
Mike> You didn't tell toArray what sort of array to create, so it
Mike> created an Object[]. Try
Mike> sortedEntryDates = (Date []) entryDate.toArray(new
Mike> Date[entryDate.size()]);
Okay, great, that worked. What am I missing about casting from Object
to Date? I've looked at some discussions of casting in my books but
it is not clear to me -- in fact, from my reading it would seem that
it should work. (converting object[] to date[]).
Nothing. What you're missing is that arrays (unlike generic collections)
have actual run-time types. Object[] and Date[] are different types, just
as Object and Date are, and casting from the former to the latter can fail.
Object[] oa = new Object[1];
Date[] da = new Date[1];
Object[] oa2 = da; // allowed
Date[] da2 = (Date[])oa2; // works, since it's "really" a Date[]
Date[] da3 = (Date[])oa; // fails at runtime with a ClassCastException
// since it's "really" an Object[]