18

How to convert Vector with string to String array in java?

1
  • What different approaches have you tried so far ? Commented Sep 21, 2011 at 13:09

7 Answers 7

26

Try Vector.toArray(new String[0]).

P.S. Is there a reason why you're using Vector in preference to ArrayList?

Sign up to request clarification or add additional context in comments.

5 Comments

new String[vector.size()] will give better performance as the new String[0] will be discarded.
@Dorus: Have you got any actual benchmarks to demonstrate this?
No, was basing this on the javadoc "If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection. " My own benchmark shows new String[0] is faster shame shame.
new String[0] is faster when the collection is empty and you have made it a constant (as all empty arrays of a type are basically equal). Otherwise using the actual size() is marginally faster.
P.S. Is there a reason why you're using Vector in preference to ArrayList? Maybe he didn't have a choice. What, have you never updated or used code that you didn't write?
13
Vector<String> vector = new Vector<String>();
String[] strings = vector.toArray(new String[vector.size()]);

Note that it is more efficient to pass a correctly-sized array new String[vector.size()] into the method, because in this case the method will use that array. Passing in new String[0] results in that array being discarded.

Here's the javadoc excerpt that describes this

Parameters:
a - the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

2 Comments

I just tried this, looks like new String[0] is somehow faster. Oops :)
@Dorus - I don't know what you "tried", but what I said remains true - see edited question for javadoc reference
3

here is the simple example

Vector<String> v = new Vector<String>();
String [] s = v.toArray(new String[v.size()]);

Comments

3

simplest method would be String [] myArray = myVector.toArray(new String[0]);

Comments

1

try this example

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

Comments

0

Try this:

vector.toArray(new String[0]);

Edit: I just tried it out, new String[vector.size()] is slower then new String[0]. So ignore what i said before about vector.size(). String[0] is also shorter to write anyway.

Comments

0

Vector.ToArray(T[])

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.