java:我如何创建一个支持任意数量参数的函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4215698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java: how can i create a function that supports any number of parameters?
提问by ufk
is it possible to create a function in java that supports any number of parameters and then to be able to iterate through each of the parameter provided to the function ?
是否可以在 java 中创建一个支持任意数量参数的函数,然后能够遍历提供给该函数的每个参数?
thanks
谢谢
kfir
克菲尔
回答by wkl
Java has had varargssince Java 1.5 (released September 2004).
自 Java 1.5(2004 年 9 月发布)以来,Java 就有了可变参数。
A simple example looks like this...
一个简单的例子看起来像这样......
public void func(String ... strings) {
for (String s : strings)
System.out.println(s);
}
Note that if you wanted to require that some minimal number of arguments has to be passed to a function, while still allowing for variable arguments, you should do something like this. For example, if you had a function that needed at least one string, and then a variable length argument list:
请注意,如果您想要求必须将一些最少数量的参数传递给函数,同时仍然允许可变参数,您应该这样做。例如,如果您有一个至少需要一个字符串的函数,然后是一个可变长度的参数列表:
public void func2(String s1, String ... strings) {
}
回答by kgiannakakis
As other have pointed out you can use Varargs:
正如其他人指出的那样,您可以使用 Varargs:
void myMethod(Object... args)
This is actually equivalent to:
这实际上相当于:
void myMethod(Object[] args)
In fact the compiler converts the first form to the second - there is no difference in byte code. All arguments must be of the same type, so if you want to use arguments with different types you need to use an Object type and do the necessary casting.
事实上,编译器将第一种形式转换为第二种形式——字节码没有区别。所有参数必须是相同的类型,所以如果你想使用不同类型的参数,你需要使用 Object 类型并进行必要的转换。