This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes toArray(arr[]) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "toArray(arr[])" Watch "toArray(arr[])" New topic
Author

toArray(arr[])

Lucky J Verma
Ranch Hand

Joined: Apr 11, 2007
Posts: 278
I have a doubt with the concept of Collection.toArray() method
1.I could really get the difference between
toArray() and toArray(arr[])
2.
In ,my code snippet , even after using toarray(some array) syntax ,i have to explicitly cast my Object array to String ,otherwsie ClassCastException comes .

hashset = is some HashSet Collection having Strings
//Converting HashSet to objectArray for Sorting elements
String obj[]=(String [])hashset.toArray(new String[2]);


Object obj1[]=hashset.toArray();
Arrays.sort(obj);
Arrays.sort(obj1);
//Sorting string array
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791

String obj[]=(String [])hashset.toArray(new String[2]);


Yes, you still have to cast the results of toArray to String[]. The toArray method here well and truly does return a String[] but the compiler can't know that. The compiler only knows the signature of toArray which promises to return Object[]. Here you have the confidence to tell the JVM at runtime to do the cast.

Have you looked into Generics in Java 5 and later? They allow us to eliminate some, but not all, cast operations like this.

Now we've told the compiler that the set will only contain Strings and the compiler enforces that rule so it knows that toArray will return String[].
[ June 16, 2007: Message edited by: Stan James ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: toArray(arr[])