简体   繁体   English

在Java中将ArrayList作为泛型参数传递

[英]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: 我有一个ArrayList<String> ,我需要传递此ArrayList中的每个字符串,作为此函数的参数:

protected Void myFunction(String... params)

NOTE: I can't modify myFunction 注意:我无法修改myFunction

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

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

1.To pass it as individual String: 1.要将其作为单独的字符串传递:

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

2.To pass an Array of String. 2.传递一个字符串数组。

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

Convert the arraylist into array of String and then pass it 将arraylist转换为String数组,然后将其传递

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() 检查此内容: 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: 只需在参数中传递ArrayList,然后在方法内部使用foreach迭代arraylist即可:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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