jQuery in Action, 2nd edition*
The moose likes Java in General and the fly likes casting of an ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "casting of an ArrayList" Watch "casting of an ArrayList" New topic
Author

casting of an ArrayList

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi Folks,
is it possible to get a String[] from an ArrayList ??
What i think of specially is ArrayList.toArray()
but this returns an Object[]
I tried it with the following line of code:
String[] temp = (String[])list.toArray();
but this throws a class cast exception. Any idea ??
Thx
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

Try this instead:

check out the API for ArrayList.toArray(Object[])

toArray
public Object[] toArray(Object[]´┐Ża)
Returns an array containing all of the elements in this list in the correct order. The runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.
If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements

Hope that helps!
[ June 19, 2002: Message edited by: Jessica Sant ]

- Jess
Blog:KnitClimbJava | Twitter: jsant | Ravelry: wingedsheep
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: casting of an ArrayList
 
Similar Threads
Head First Java Ch.9 Constructors and Garbage Collection
What the use and benefit of writing also tell me the difference
JAVA Swing JTree and ArrayList
Parsing a text file to an arraylist
How to print the elements of an arraylist that contains a hashmap