File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Mock question of collection's toArray method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Mock question of collection Watch "Mock question of collection New topic
Author

Mock question of collection's toArray method

Sam Sunamin
Ranch Hand

Joined: Mar 16, 2007
Posts: 113


The above code have runtime exception ClassCastException on line 1 since s.toArray return object[], and it cannot cast to String[].

Do you guys have any way to change it to String[].

Thanks in advance.


Yours Sam<br />SCJP5.0 97%<br />SCBCD5.0 72%
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Yes there is another method called toArray that accepts a reference to an array.
Sam Sunamin
Ranch Hand

Joined: Mar 16, 2007
Posts: 113
I know that API. s.toArray(T[] a). But I do not have an array before calling toArray method.

So I cannot do it in that way.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Yes you can create one.

You know the type of the array, and you know how many elements will be in the array.
Sam Sunamin
Ranch Hand

Joined: Mar 16, 2007
Posts: 113
Then why I need toArray method? For fun.

Just kidding. I mean I need use toArray method to get an array. If I already have an array, why I need use toArray method.

You know what I mean.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
The reason is simple.

If you have a Set containing objects that are of type String, if you only use the toArray() method, then you get an array of type Object[].

You cannot cast this to String[].

If you wanted to have a String array, you would have to create a new String array and copy the elements from the Object array, casting each one to type String if the type of the Object were String.

With the version of toArray that accepts an array, the implementation can create an array of the specified type and populate it with the elements in the Collection.

Before generics, you would have to cast the result of the method to that particular type of array reference.

With generics, you are returned a reference to an array of the type in the Collection.
Sam Sunamin
Ranch Hand

Joined: Mar 16, 2007
Posts: 113
Thank you Keith . I know what you mean.

I change


to



Then it works.
 
wood burning stoves
 
subject: Mock question of collection's toArray method