0

I'm trying to convert a Vector of Objects that have a toString() method using

(String[]) mObjectVector.toArray(new String[mObjectVector.size()])

or

(String[]) mObjectVector.toArray(new Object[mObjectVector.size()])

However, it gives me the following errors:

java.lang.ArrayStoreException: source[0] of type .../myObjectType; cannot be stored in destination array of type [Ljava/lang/String;

and

java.lang.ClassCastException: [Ljava.lang.Object;

What is wrong?

2 Answers 2

3

You cannot cast an object into the return type of that objects toString method. You have to build a new array by iterating over the Vector objects while calling toString.

String[] stringArray = new String[mObjectVector.size()];
for (int i=0; i < mObjectVector.size(); i++) {
   stringArray[i] = mObjectVector.get(i).toString();
}
Sign up to request clarification or add additional context in comments.

Comments

0

i guess you cant do toArray here because your vector has custom object.

you need to manually loop the vector and call toString() on object and set it to string array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.