aspose file tools*
The moose likes Beginning Java and the fly likes Re: Convert Object array to String array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Re: Convert Object array to String array" Watch "Re: Convert Object array to String array" New topic
Author

Re: Convert Object array to String array

Joe Cheung
Ranch Hand

Joined: Oct 18, 2002
Posts: 104
Dear all,
I have the codes shown below in that I intend to convert (or cast) the Object[] to String[], how can I do that.
Vector a = new Vector();
a.add("test1");
a.add("test2");
Object[] objArray = a.toArray();
String[] strArray = (?) objArray;


Joe
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8927
    
    9

You can't convert an array to a different type, even if the element types can be converted. However, you can use System.arraycopy() to move the elements between the two arrays.
java.lang.System


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Note that there are two versions of the Vector.toArray method.
Don't use Object[] objArray = a.toArray();. Use String[] strArray = a.toArray(new String[]{}); instead.
[ April 06, 2004: Message edited by: Dirk Schreckmann ]

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

Don't use Object[] objArray = a.toArray();. Use String[] strArray = a.toArray(new String[]{}); instead.

Or better still (for performance reasons),


Tony Morris
Java Q&A (FAQ, Trivia)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Re: Convert Object array to String array