• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Re: Convert Object array to String array

 
Joe Cheung
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 Ess
Bartender
Posts: 9256
9
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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

Or better still (for performance reasons),
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic