Java fn(字符串…参数)与fn(字符串[]参数)的差异

Java fn(字符串…参数)与fn(字符串[]参数)的差异,java,variadic-functions,Java,Variadic Functions,此语法有什么用处: function(String... args) 这和写作一样吗 function(String[] args) 只有在调用此方法时才有差异,或者是否有任何其他功能与之相关?在接收器大小上,您将获得一个字符串数组。区别仅在调用端。两者之间的唯一区别是调用函数的方式。使用字符串var args,可以省略数组创建 public static void main(String[] args) { callMe1(new String[] {"a", "

此语法有什么用处:

    function(String... args)
这和写作一样吗

    function(String[] args) 

只有在调用此方法时才有差异,或者是否有任何其他功能与之相关?

在接收器大小上,您将获得一个字符串数组。区别仅在调用端。

两者之间的唯一区别是调用函数的方式。使用字符串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);
    }
}

将第一个函数调用为:

function(arg1, arg2, arg3);
而第二个:

String [] args = new String[3];
args[0] = "";
args[1] = "";
args[2] = "";
function(args);
使用varargs(
String…
)可以通过以下方式调用该方法:

function(arg1);
function(arg1, arg2);
function(arg1, arg2, arg3);

使用数组(
String[]
)无法做到这一点。

只有在调用该方法时才有区别。第二个表单必须用数组调用,第一个表单可以用数组调用(就像第二个表单一样,是的,根据Java标准这是有效的),或者用字符串列表(多个字符串用逗号分隔)调用,或者根本没有参数(第二个表单必须始终有一个,至少必须传递null)

它在句法上是糖。实际上,编译器

function(s1, s2, s3);
进入


内部。

另一个需要强调的主要优点是,正如Mecki在回答中所说的,即使没有单个var arg参数,也可以调用var args函数。在上面的示例中,callMe2();不产生编译错误。另一个需要强调的主要优点是,正如Mecki在回答中所说的,即使没有单个var arg参数,也可以调用var 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);
        }
    }
}
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);
        }
    }
}