How to add all items in a String array to a vector in Java? How to add all items in a String array to a vector in Java? arrays arrays

How to add all items in a String array to a vector in Java?


Collections.addAll(myVector, myArray);

This is the preferred way to add the contents of an array into a collection (such as a vector).

https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#addAll-java.util.Collection-T...-

Adds all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.


The vector.addAll()takes a Collection in parameter.In order to convert array to Collection, you can use Arrays.asList():

My_Vector.addAll(Arrays.asList(My_Array));


My_Vector.addAll(Arrays.asList(My_Array));

If you notice, Collection.addAll takes a Collection argument. A Java array is not a Collection, but Arrays.asList, in combination with Collection.toArray, is the "bridge between array-based and collection-based APIs".

Alternatively, for the specific purpose of adding elements from an array to a Collection, you can also use the static helper method addAll from the Collections class.

Collections.addAll(My_Vector, My_Array);