• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Ron McLeod
  • Tim Moores
  • salvin francis
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Vijitha Kumara

toArray(arr[])  RSS feed

 
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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 ]
 
Have you no shame? Have you no decency? Have you no tiny ad?
global solutions you can do in your home or backyard
https://coderanch.com/t/708587/global-solutions-home-backyard
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!