Nrj*_*Nrj 62 java variadic-functions
这个语法对以下内容有用:
function(String... args)
Run Code Online (Sandbox Code Playgroud)
和写作一样吗?
function(String[] args)
Run Code Online (Sandbox Code Playgroud)
仅在调用此方法时有区别或是否还有其他功能?
bru*_*nde 85
两者之间的唯一区别是你调用函数的方式.使用String var args可以省略数组创建.
public static void main(String[] args) {
callMe1(new String[] {"a", "b", "c"});
callMe2("a", "b", "c");
// You can also do this
// callMe2(new String[] {"a", "b", "c"});
}
public static void callMe1(String[] args) {
System.out.println(args.getClass() == String[].class);
for (String s : args) {
System.out.println(s);
}
}
public static void callMe2(String... args) {
System.out.println(args.getClass() == String[].class);
for (String s : args) {
System.out.println(s);
}
}
Run Code Online (Sandbox Code Playgroud)
Mec*_*cki 20
差异仅在调用方法时.必须使用数组调用第二个表单,第一个表单可以使用数组调用(就像第二个表单一样,是的,根据Java标准这是有效的)或者使用字符串列表(多个字符串用逗号分隔)或根本没有参数(第二个必须有一个,必须至少传递null).
它在语法上是糖.实际上编译器会转
function(s1, s2, s3);
Run Code Online (Sandbox Code Playgroud)
成
function(new String[] { s1, s2, s3 });
Run Code Online (Sandbox Code Playgroud)
内部.
mic*_*con 11
使用varargs(String...),您可以这样调用方法:
function(arg1);
function(arg1, arg2);
function(arg1, arg2, arg3);
Run Code Online (Sandbox Code Playgroud)
你不能用array(String[])做到这一点
您将第一个函数称为:
function(arg1, arg2, arg3);
Run Code Online (Sandbox Code Playgroud)
而第二个:
String [] args = new String[3];
args[0] = "";
args[1] = "";
args[2] = "";
function(args);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62570 次 |
| 最近记录: |