方法签名中的Java“参数”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/519752/
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 "params" in method signature?
提问by Omar Kooheji
In C#, if you want a method to have an indeterminate number of parameters, you can make the final parameter in the method signature a params
so that the method parameter looks like an array but allows everyone using the method to pass as many parameters of that type as the caller wants.
在C#中,如果你想让一个方法有一个不确定数量的参数,你可以在方法签名中将最后一个参数设为a,params
这样方法参数看起来像一个数组,但允许使用该方法的每个人传递尽可能多的该类型的参数如来电者所愿。
I'm fairly sure Java supports similar behaviour, but I cant find out how to do it.
我相当确定 Java 支持类似的行为,但我不知道如何去做。
采纳答案by David Grant
In Java it's called varargs, and the syntax looks like a regular parameter, but with an ellipsis ("...") after the type:
在 Java 中,它被称为varargs,其语法看起来像一个常规参数,但在类型后面有一个省略号(“...”):
public void foo(Object... bar) {
for (Object baz : bar) {
System.out.println(baz.toString());
}
}
The vararg parameter must alwaysbe the lastparameter in the method signature, and is accessed as if you received an array of that type (e.g. Object[]
in this case).
vararg 参数必须始终是方法签名中的最后一个参数,并且就像您收到该类型的数组一样进行访问(例如Object[]
在这种情况下)。
回答by Stefano Driussi
This will do the trick in Java
这将在 Java 中发挥作用
public void foo(String parameter, Object... arguments);
public void foo(String parameter, Object... arguments);
You have to add three points ...
and the varagr
parameter must be the last in the method's signature.
您必须添加三个点...
,并且varagr
参数必须是方法签名中的最后一个。
回答by Levent Divilioglu
As it is written on previous answers, it is varargs
and declared with ellipsis
(...)
正如之前的答案所写的那样,它是varargs
用ellipsis
( ...)
Moreover, you can either pass the value types and/or reference types or both mixed (google Autoboxing). Additionally you can use the method parameter as an array as shown with the printArgsAlternate
method down below.
此外,您可以传递值类型和/或引用类型或两者混合(google Autoboxing)。此外,您可以将方法参数用作数组,如printArgsAlternate
下面的方法所示。
Demo Code
演示代码
public class VarargsDemo {
public static void main(String[] args) {
printArgs(3, true, "Hello!", new Boolean(true), new Double(25.3), 'a', new Character('X'));
printArgsAlternate(3, true, "Hello!", new Boolean(true), new Double(25.3), 'a', new Character('X'));
}
private static void printArgs(Object... arguments) {
System.out.print("Arguments: ");
for(Object o : arguments)
System.out.print(o + " ");
System.out.println();
}
private static void printArgsAlternate(Object... arguments) {
System.out.print("Arguments: ");
for(int i = 0; i < arguments.length; i++)
System.out.print(arguments[i] + " ");
System.out.println();
}
}
Output
输出
Arguments: 3 true Hello! true 25.3 a X
Arguments: 3 true Hello! true 25.3 a X