File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mock question of collection's toArray method

 
Sam Sunamin
Ranch Hand
Posts: 113
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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.
 
Keith Lynn
Ranch Hand
Posts: 2399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes there is another method called toArray that accepts a reference to an array.
 
Sam Sunamin
Ranch Hand
Posts: 113
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 113
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 113
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Keith . I know what you mean.

I change


to



Then it works.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic