GVillani82
GVillani82

Reputation: 17429

Passing ArrayList as generics parameter in Java

I have a ArrayList<String> and I need to pass each String in this ArrayList, as parameter of this function:

protected Void myFunction(String... params)

NOTE: I can't modify myFunction

Upvotes: 0

Views: 1540

Answers (4)

asifsid88
asifsid88

Reputation: 4701

Convert the arraylist into array of String and then pass it

instanceName.myFunction(list.toArray(new String[list.size()]));

NOTE: You don't have to change the signature of your method.

CHECK THIS: http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#toArray()

Upvotes: 1

Agemen
Agemen

Reputation: 1535

Transform it to an array with the toArray method :

myList.toArray(new String[myList.size()]);

Upvotes: 7

Romain R
Romain R

Reputation: 41

Just pass your ArrayList in parameter and then iterate on the arraylist with a foreach inside your method:

protected void myFunction(ArrayList<String> myArrayList){
    for(String myParam : myArrayList){
        //do your stuff
    }
}

Upvotes: 0

AllTooSir
AllTooSir

Reputation: 49372

1.To pass it as individual String:

List<String> list = new ArrayList<String>();
for(String element:list){
  myFunction(element);
}

2.To pass an Array of String.

myFunction(list.toArray(new String[list.size()]));

Upvotes: 2

Related Questions