• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting of an ArrayList

 
Anonymous
Ranch Hand
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4313
Android IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic