2013-02-15 76 views
0

请告知我如何转换以下程序进入可变参数是由Java 5中引入的新功能,仪式现在我利用匿名内部数组..关于变参数和匿名阵列

public class AnnonymousArrayExample { 

    public static void main(String[] args) { 

     //calling method with anonymous array argument 
     System.out.println("first total of numbers: " + sum(new int[]{ 1, 2,3,4})); 
     System.out.println("second total of numbers: " + sum(new int[]{ 1, 2,3,4,5,6,})); 

    } 

    //method which takes an array as argument 
    public static int sum(int[] numbers){ 
     int total = 0; 
     for(int i: numbers){ 
      total = total + i; 
     } 
     return total; 
    } 
} 

回答

2

作出这样 public static int sum(int ... numbers)

下你的方法的签名是有效的调用

sum(); 
sum(1,2,3); 
sum(1,2,3,4,5); 
sum(new int[] {1,2,3}) 
2

使用VAR-ARGS

public static int sum(int... numbers){} 

请参见

+0

调用部分还需要做些什么改变,请指教。 – user2045633 2013-02-15 06:42:59

+0

调用部分没有变化 – 2013-02-15 06:43:17

+0

你可以称它为sum(1,2,3,4); //任何数量的参数 – 2013-02-15 06:46:28

0

使用varargs (...)改变你的方法签名public static int sum(int... numbers)

public static int sum(int... numbers){ 
     int total = 0; 
     for(int i: numbers){ 
      total = total + i; 
     } 
     return total; 
} 

...

System.out.println("first total of numbers: " + sum(new int[]{ 1, 2,3,4})); 
System.out.println("second total of numbers: " + sum(new int[]{ 1, 2,3,4,5,6,})); 

更多关于varargs - Reference Document

0

只要改变你的参数声明(从[]到...),并在调用部分没有变化:

public class AnnonymousArrayExample { 

    public static void main(String[] args) { 

     // calling method with anonymous array argument 
     System.out.println("first total of numbers: " 
       + sum(new int[] { 1, 2, 3, 4 })); 
     System.out.println("second total of numbers: " 
       + sum(new int[] { 1, 2, 3, 4, 5, 6, })); 

    } 

    // method which takes an array as argument 
    public static int sum(int... numbers) { 
     int total = 0; 
     for (int i : numbers) { 
      total = total + i; 
     } 
     return total; 
    } 
} 
0

总和方法应声明如下:

public static int sum(int ... numbers) 

和呼叫看起来应该像:

sum(1,2,3,4,5) 
1

有没有这样的事,作为一个“匿名内部阵” - 你有什么根本就一个array creation expression

要使用可变参数数组,你只需要改变这样的方法声明:

public static int sum(int... numbers) { 
    // Code as before - the type of numbers will still be int[] 
} 

而且调用代码更改为:

System.out.println("first total of numbers: " + sum(1, 2, 3, 4)); 

了解更多详情,或Java 1.5 language guidesection 8.4.1 of the Java Language Specification

+0

您最大的先生! – Shivam 2013-02-15 07:09:37

0

总和功能应该是这样的:

public static int sum(int... numbers) { 
    int total = 0; 
    for (int i : numbers) { 
    total = total + i; 
    } 
    return total; 
} 

它看起来几乎张玉峰,你原来的代码 - 有很好的理由。据我所知,在内部,可变参数使用数组进行编译。两个函数的签名都是相同的 - 您无法将两者都保存在代码中。所以“省略号”语法只是语法糖。

和函数的调用:

int total = sum(1,2,3,4); 

看起来比较清爽语法,但引擎盖下,它是与您的原代码 - 编译器会创建一个数组,使用给定值初始化和将它作为参数传递给函数。