I want to convert a vector into a string array. I have put in my code:

criteria = (String []) tokenVector.toArray();

I get a ClassCastExceptionError (I can understand why since Vector holds objects which are 'bigger' than strings) - and yet I cannot understand how to resolve it - any ideas would be welcome.

you need to use an overloaded version of toArray() which takes as argument an array to put the data in (if it fits).
The usual way to use this version is as follows:

criteria = (String[])tokenVector.toArray(new String[0]);

which gives the function a zero-length array of String with the only purpose to use this array as an indication of the type of array you want it to return.
Alternatively you could initialise the array with the correct length and pass it:

String[] criteria = new String[tokenVector.size()];
tokenVector.toArray(criteria);

Thanks a lot!!
The solution has helped me with ArrayList<String> to String[] conversion also in java.

hi:
you can do that like that is
package com.structure;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TestArray {
static List<String> list = new ArrayList<String>();
// static Object[] state;
public static void main(String agrs[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Please input number:");
int num = scan.nextInt();
System.out.println("Please input your String:");
for (int i = 0; i < num; i++) {
list.add((String) scan.next());
}
for (Object str : exchangeArray(list)) {
System.out.println(str);
}
}
public static Object[] exchangeArray(List list) {
return list.toArray();
}
}

hi:
you can do that like that is
package com.structure;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TestArray {
static List<String> list = new ArrayList<String>();
// static Object[] state;
public static void main(String agrs[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Please input number:");
int num = scan.nextInt();
System.out.println("Please input your String:");
for (int i = 0; i < num; i++) {
list.add((String) scan.next());
}
for (Object str : exchangeArray(list)) {
System.out.println(str);
}
}
public static Object[] exchangeArray(List list) {
return list.toArray();
}
}

He could do it something like, but then the question is, Why would he, when he as already been shown two better, and easier to use, solutions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.