File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes Question about casting. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "Question about casting." Watch "Question about casting." New topic
Author

Question about casting.

James Turner
Ranch Hand

Joined: May 10, 2004
Posts: 194
Hi all,

I have a problem which I am not sure why its happening. I have an ArrayList which i add String arrays to (String[]). Then I call the ArrayList's toArray method to convert the array list to an array of String arrays, i.e. a 2 dimensional array.

A call to: myArrayList.toArray(new String[0]); will return an array of Strings (String[]). If i was to have a list of String[] arrays in the array list already, shouldn't I be able to cast the returned String array to a 2 dimensional array? (String[][]).

When I do that I get a class cast exception. Dosn't it make sence what I am doing? I hope I made myself clear.

Thanx for your help.

James


James<br />SCJP 1.4 - 92%<br />SCJD - 93%<br />SCWCD 1.4 - 95%<br />SCBCD 1.3 - 100%<br />SCEA - 92%
Hanna Habashy
Ranch Hand

Joined: Aug 20, 2003
Posts: 532
hi James:
arrays are java.lang.Object, no matter what type they are holding. So, an ArrayList that contains String[] arrays, is an ArrayList contains objects.
If you want to convert the ArrayList to an ordinarry array, you need to type:

Object[] myObjectsArray = myArrayList.toArray(new Object[0]);

then, if you want to get the value of the objects inside myObjectsArray, you type:

String[] myStringArray = (String[])myObjectArray[n];//n is the index number

now you end up with a plain String array- String[].


SCJD 1.4<br />SCJP 1.4<br />-----------------------------------<br />"With regard to excellence, it is not enough to know, but we must try to have and use it.<br />" Aristotle
James Turner
Ranch Hand

Joined: May 10, 2004
Posts: 194
Thanx for your help.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question about casting.