Vector into String array

I think I used to know how to do this once upon a time, but that was a while ago. I have a vector full of string objects, and I need to turn it into a String array.

String[] sarray = vector.toArray();

Doesn’t work because the vector method is outputing an Object array instead of a String array. I’ve tried casting it like this:

String[] sarray = (String[])vector.toArray();

And even though that will compile, it produces an error at run time.

Exception in thread “main” java.lang.ClassCastException: java.util.Arrays$ArrayList

Is there something simple I’m overlooking, or do I simply need to use a loop to step through the vector and assign elements to the string array element by element? Thanks :).

String[] sarray = (String[]) vector.toArray(new String[0]);

Kev

I also used this until I came across the source code,


    public synchronized <T> T[] toArray(T[] a) {
        if (a.length < elementCount)
            return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());

	System.arraycopy(elementData, 0, a, 0, elementCount);

        if (a.length > elementCount)
            a[elementCount] = null;

        return a;
    }

(note: this is from Java 6, which introduced ‘Arrays.copyOf’)

which made me assume that the follwing soulde be faster:


String[] sarray = vector.toArray(new String[vector.size()]);

(further, the cast shouldn’t be necessary using java 5+)

Also, prefer ArrayList to Vector… Vector has synchronization that is usually useless.

Thank you very much for all of the replies. All of them seem to be more resource-friendly than spinning through a for loop.