JAVA可变参数

public class test1 {
    public static void main(String[] args) {
        canshu1 a = new canshu1();
        System.out.println("----数组传递----");
        String[] a1 = new String[] {"123","456","567"};
        a.showInfo(a1);
        System.out.println("...形式可以接收数组");
        a.showInfo1(a1);
        System.out.println("----传字符串----");
        a.showInfo1("aaa","bbb");
        System.out.println("----也可以传多个数字----");
        a.showInfo2(1,2,3,4,5);
        
        //a.showInfo(null);//没有参数,传递null,代表数组为空
        //a.showInfo1();//没有参数时,...形式不用任何参数
        
        a.showInfo3("love", 1,2,3);
        
    }
}
class canshu1 {
    
    public void showInfo(String a[]) {
        for(int i = 0;i < a.length;i++)
            System.out.println(a[i]);
    }
    public void showInfo1(String...a)
    {
        for(int i = 0;i < a.length;i++)
            System.out.println(a[i]);
    }
    public void showInfo2(int...b) {
        for(int i = 0;i < b.length;i++)
            System.out.println(b[i]);
    }
    //方法的参数部分有可变形参时,要放在形参声明的最后
    public void showInfo3(String n,int...c)
    {
        System.out.println(n);
        for(int i = 0;i < c.length;i++)
        {
            System.out.print(c[i]);
        }
    }
}

输出:

----数组传递----
123
456
567
...形式可以接收数组
123
456
567
----传字符串----
aaa
bbb
----也可以传多个数字----
1
2
3
4
5
love
123
原文地址:https://www.cnblogs.com/lintianxiajun/p/12834458.html