Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

My code looks like this :

Vector<String> My_Vector=new Vector<String>(); String My_Array[]=new String[100];  for (int i=0;i<100;i++) My_Array[i]="Item_"+i; ...... My_Vector.addAll(My_Array); 

But I got an error message, what's the right way to do it, without looping to add each item ?

Frank

like image 230
Frank Avatar asked Mar 04 '10 23:03

Frank


People also ask

How do you add elements to a string array in Java?

By using ArrayList as intermediate storage:Create an ArrayList with the original array, using asList() method. Simply add the required element in the list using add() method. Convert the list to an array using toArray() method.


2 Answers

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.

like image 182
Chris Jester-Young Avatar answered Oct 12 '22 18:10

Chris Jester-Young


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)); 
like image 39
Yannick Loriot Avatar answered Oct 12 '22 18:10

Yannick Loriot