user3182445
user3182445

Reputation: 363

toArray() method of Vector<> class

A Vector may contain objects of different types. Does calling the toArray() method return an Object[] array or an array of specific objects (Eg. Integer, Double)? I'm guessing it does not return specific object arrays since an array can have objects of one type only.

Is there any way of creating multiple object specific arrays depending on the object types contained in a Vector?

Upvotes: 0

Views: 566

Answers (2)

dkatzel
dkatzel

Reputation: 31648

Both Vector and any Collection object have 2 methods : toArray() which returns Object[] and toArray(T[]) which you have to provide an array of the correct type.

If you have a Collection of Integer this will work:

Vector<Integer> vector = ...
 Integer[] myInts = vector.toArray(new Integer[vector.size()]);

Note that I created an array of the size of the vector. This isn't actually required but will speed things up since otherwise Java will have to use reflection to figure out the type and create an array of the correct size.

If your Collection has a mixture of different incompatiable types, and you provide an array that can't be used to store them all, the JVM will throw an java.lang.ArrayStoreException at runtime when you call toArray(array[])

    Vector<Object> vector = new Vector<>();
    vector.add(Integer.valueOf(2));
    vector.add(Double.valueOf(3.14));

    vector.toArray(new Integer[vector.size()]); //<-- throws ArrayStoreException

However, using an array of objects that all the objects in the vector are compatiable with is OK.

This will work since both Integer and Double extend Number

Number[] myNumbers = vector.toArray(new Number[vector.size()]);

Upvotes: 6

ControlAltDel
ControlAltDel

Reputation: 35011

Because you can only return 1 object from the method, the way to do this would be to create a ManyMap, indexing the Class of each object with a list/array of the objects that are of that class

Upvotes: 1

Related Questions