This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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: 8705
    
    6

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
 
Similar Threads
Autoboxing question
Help! Invoke won't take my Object Array parameter
Assign two dimensional string array to one dimensional object array
Correction for the given code fragment
Check the object array instance of string array