File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JSP and the fly likes How do I cast from Vector to String Array? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » JSP
Bookmark "How do I cast from Vector to String Array?" Watch "How do I cast from Vector to String Array?" New topic

How do I cast from Vector to String Array?

Leon Gelbak

Joined: Jul 15, 2002
Posts: 3
I need to cast from an existing vector of string values to a new String Array. ie.
String myArray[] = (String[]) myVector.toArray();
When I do this, it crashes...
please help.. already wrote around it a function to return a string array after passing the vector into it, but thats stupid, and its late and any help on the correct syntax would be greatly appreciated.
chanoch wiggers
Ranch Hand

Joined: May 24, 2001
Posts: 245
Object[] yourArray = yourVector.toArray()
etc. Vector is not of type array so you cant cast to an array. You can retrieve the array as objects and then cast each object to string as you are retrieving it
for(blah blah) {
String thisString = (String)yourArray[i];

chanoch<p><a href="" target="_blank" rel="nofollow">Author of Professional Apache Tomcat</a></p>
Leon Gelbak

Joined: Jul 15, 2002
Posts: 3
I tried that syntax. Below is the result
org.apache.jasper.JasperException: Unable to compile class for JSPD:\inetpub\wwwroot\dev\localhost_8080\ Incompatible type for declaration. Explicit cast needed to convert java.lang.Object[] to java.lang.String[].
String[] amyRoles = myRoles.toArray();
1 error
Frank Carver

Joined: Jan 07, 1999
Posts: 6920
That's why the original code said Object[] The method as described returns an Object array, the elements of which just happen to be Strings, not a String array.
There are two forms of toArray.
One, as described above, creates an Object[] of the correct size and copies all the elements of the collection into it.
Another, not mentioned yet, takes a "prototype" object as a parameter, and creates a return array of the same type.
So if you really need a String[] (and can't take the hit of just casting the Objects from the array to String when they are extracted), then do something like:

Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Joe Ess

Joined: Oct 29, 2001
Posts: 9189

Originally posted by Frank Carver:

There are two forms of toArray.

Sweet. Never noticed that before. I've always used System.arraycopy:
Object arr1[] = {"asdf", "jkl;", "qwer", "uiop"};
String arr2[];
System.arraycopy(arr1, 0, arr2, 0, arr1.length);

[How To Ask Questions On JavaRanch]
I agree. Here's the link:
subject: How do I cast from Vector to String Array?
It's not a secret anymore!