这个语法有什么用:
function(String... args)
这和写作一样吗
function(String[] args)
仅在调用此方法时有所不同,或者是否涉及其他任何功能?
这个语法有什么用:
function(String... args)
这和写作一样吗
function(String[] args)
仅在调用此方法时有所不同,或者是否涉及其他任何功能?
两者之间的唯一区别是调用函数的方式。使用 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);
}
}
区别仅在于调用该方法时。第二种形式必须用数组调用,第一种形式可以用数组调用(就像第二种形式一样,是的,这根据 Java 标准是有效的)或字符串列表(多个字符串用逗号分隔)或根本没有参数(第二个总是必须有一个,至少必须传递 null )。
它在语法上是糖。实际上编译器转
function(s1, s2, s3);
进入
function(new String[] { s1, s2, s3 });
内部。
使用 varargs ( String...
) 您可以这样调用该方法:
function(arg1);
function(arg1, arg2);
function(arg1, arg2, arg3);
你不能用数组 ( String[]
)做到这一点
您将第一个函数称为:
function(arg1, arg2, arg3);
而第二个:
String [] args = new String[3];
args[0] = "";
args[1] = "";
args[2] = "";
function(args);
在接收器大小上,您将获得一个字符串数组。区别仅在于调用方。
class StringArray1
{
public static void main(String[] args) {
callMe1(new String[] {"a", "b", "c"});
callMe2(1,"a", "b", "c");
callMe2(2);
// You can also do this
// callMe2(3, 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(int i,String... args) {
System.out.println(args.getClass() == String[].class);
for (String s : args) {
System.out.println(s);
}
}
}