我们有一个方法:
public void foo (String s1, String s2, String s3) {
...
}
以及精选集。也许 hashmap,也许 list,都没有关系。
有没有办法将集合“转换”为方法参数?像这样的东西:
public void foo (getParamters(map)) { ... }
当然可以
public void foo (map.get(0), map.get(1), map.get(3)) { ... }
但我正在考虑一些更自动化的东西,它可以帮助我解决更大的问题。
最佳答案
您可以将集合转换为数组并将数组传递给方法:
public void foo (String... s) {
...
}
...
String[] arr = map.keySet().toArray (new String[0]);
foo (arr);
由于事先不知道集合中的元素数量,因此使用可变参数声明方法比在 foo (String s1, String s2, String s3) 中声明固定数量的参数更有意义
。
关于java - 收集到方法参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28894930/