2008-11-19 101 views

回答

78

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

在接收器大小上,您将得到一个String数组。区别仅在于主叫方。

7

你打电话的第一个函数为:

function(arg1, arg2, arg3); 

,而第二个:

String [] args = new String[3]; 
args[0] = ""; 
args[1] = ""; 
args[2] = ""; 
function(args); 
8

可变参数(String...),你可以调用的方法是这样的:

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

Y ou不能这样做与数组(String[]

+0

我最喜欢的答案 – 2014-03-05 14:00:11

17

区别只在调用该方法时。第二种形式必须用一个数组来调用,第一种形式可以用一个数组来调用(就像第二种形式一样,是的,这是根据Java标准有效的)或者一串字符串(用逗号分隔的多个字符串)或根本没有参数(第二个总是必须有一个,至少必须通过null)。

它是语法上的糖。实际上,编译器开启

function(s1, s2, s3); 

function(new String[] { s1, s2, s3 }); 

内部。

2
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); 
     } 
    } 
} 
相关问题