我想这样做:
ArrayList<String> strings = new ArrayList<>();
//build a collection of Strings
callMethod(strings);
"callMethod"是遗留的(在遗留项目中),所以我不能更改它。
它的签名是这样的:
private void callMethod(String... input){
// and so forth...
如何将字符串集合传递给callMethod方法?
只需将列表转换为字符串数组(varargs在底层变成数组:"如果形式形参是可变参数,则声明的类型是第10.2节指定的数组类型">):
callMethod(strings.toArray(new String[0]));
将字符串列表转换为字符串数组。
ArrayList<String> strings = new ArrayList<>();
callMethod(strings.toArray(new String[strings.size()]));
如果你有一个带有可变参数的方法,你有两个选择:
- 将集合中的每个项作为单个参数传递,或者
- 将集合作为数组传递
示例方法:
/**
* <p>
* Prints the {@link String}s passed
* </p>
*
* @param item the bunch of character sequences to be printed
*/
public static void print(String... item) {
System.out.println(String.join(" ", item));
}
你可以这样使用:
public static void main(String[] args) throws IOException {
// some example list of Strings
List<String> words = new ArrayList<>();
words.add("You");
words.add("can");
words.add("pass");
words.add("items");
words.add("in");
words.add("an");
words.add("Array");
// first thing you can do is passing each item of the list to the method
print(words.get(0), words.get(1), words.get(2), words.get(3), words.get(4), words.get(5), words.get(6));
// but better pass an array, String[] here
String[] arrWords = words.stream().toArray(String[]::new);
print(arrWords);
}
输出You can pass items in an Array
You can pass items in an Array
public void method() {
ArrayList<String> strings = new ArrayList<>();
//1. calling method by passing the array
callMethod(strings.toArray(new String[strings.size()]));
//2. Using stream method to convert list into array
callMethod(strings.stream().toArray(String[]::new));
}
// method having array of String as parameter
public static void callMethod(String... input){
// TODO Method stub
}