File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "casting of an ArrayList" Watch "casting of an ArrayList" New topic

casting of an ArrayList

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 ??
Jessica Sant

Joined: Oct 17, 2001
Posts: 4313

Try this instead:

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

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
I agree. Here's the link:
subject: casting of an ArrayList
It's not a secret anymore!