Home arrow static arrow Java Programming [Archive] - just can't cast Object[] to MyObject[]?
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - just can't cast Object[] to MyObject[]?
This topic has 4 replies on 1 page.

Posts:12
Registered: 7/24/04
just can't cast Object[] to MyObject[]?  
Jul 24, 2004 10:45 AM



 
My program has an arraylist to hold an array of MyObjects with variable number. At the end of the program, I want to return the result as MyObject[]. So I write

return (MyObject[])myArrayList.toArray();

but the run time returns me java.lang.ClassCastException. So does that mean I have to do it by one-by-one casting? That would be aweful. Does anybody have a smart way to do this?
thanks

Chen
 

Posts:709
Registered: 5/12/04
Re: just can't cast Object[] to MyObject[]?  
Jul 24, 2004 10:57 AM (reply 1 of 4)



 
How about a loop?
 

Posts:18,384
Registered: 21.03.00
Re: just can't cast Object[] to MyObject[]?  
Jul 24, 2004 11:21 AM (reply 2 of 4)



 
Hi,

See the javadoc for toArray(Object[]´┐Ża)

/Kaj
 

Posts:24,036
Registered: 2/3/03
Re: just can't cast Object[] to MyObject[]?  
Jul 24, 2004 1:31 PM (reply 3 of 4)



 
return (MyObject[])myArrayList.toArray();
return (MyObject[]) myArrayList.toArray(new MyObject[myArrayList.size()]);
 

Posts:12
Registered: 7/24/04
Re: just can't cast Object[] to MyObject[]?  
Jul 26, 2004 7:24 AM (reply 4 of 4)



 
thanks. it works.
 
This topic has 4 replies on 1 page.