0

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

1
  • 2
    The parameter is a String array , why do you need to pass as individual String ? Commented Apr 30, 2013 at 12:28

4 Answers 4

7

Transform it to an array with the toArray method :

myList.toArray(new String[myList.size()]);
Sign up to request clarification or add additional context in comments.

Comments

2

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()]));

Comments

1

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()

2 Comments

You'll have Object[], not String[]. There's another toArray method that has a more accurate return type.
Parameterless toArray() returns Object[] only! You need to invoke toArray(new String[0]) (or better, supply the correct size)
0

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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.