简体   繁体   中英

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

使用toArray方法将其转换为数组:

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM