How to convert Vector with string to String array in java?
7 Answers
Try Vector.toArray(new String[0]).
P.S. Is there a reason why you're using Vector in preference to ArrayList?
5 Comments
Dorus
new String[vector.size()] will give better performance as the new String[0] will be discarded.NPE
@Dorus: Have you got any actual benchmarks to demonstrate this?
Dorus
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.
Peter Lawrey
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.
Abu Sulaiman
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?
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.