【Java学习笔记之二十七】Java8中传多个参数时的方法

118 阅读1分钟

java中传参数时,在类型后面跟"..."的使用:



public static void main(String[] args){
testStringArgs();//无参数传入
testStringArgs("one");//一个参数传入
testStringArgs("one","two","three");//3个String参数传入
testStringArgs(new String[]{"one","two","three"});//可以看到传入三个String参数和传入一个长度为3的数组结果一样,再看例子


**//  testStringArgs(new String[]{"one","two","three"},new String[]{"one","two","three"});//这样写会提示错误。
**      
testIntegerArgs();
testIntegerArgs(1);
testIntegerArgs(1,2,3);
testIntegerArgs(new Integer[]{1,2,3});
}

**//有点类似于 () 和  (String s1,String s2......)  和  (String[] s)    3个合在一起的功能。
**     public static void testStringArgs(String... s){
if(s.length==0){
System.out.println("0个参数传入");
}else if(s.length==1){
System.out.println("1个参数传入");
}else{   
System.out.println("多个参数传入,每个参数如下:");
for(int i=0;i<s.length;i++){
System.out.println("第"+(i+1)+"个参数是"+s[i]+";");
}   
System.out.println();
}
}

public static void testIntegerArgs(Integer... ints){
if(ints.length==0){
System.out.println("0个Integer参数传入");
}else if(ints.length==1){
System.out.println("1个Integer参数传入");
}else{   
System.out.println("多个参数传入,每个参数如下:");
for(int i=0;i<ints.length;i++){
System.out.println("第"+(i+1)+"个Integer参数是"+ints[i]+";");
}   
System.out.println();
}
}

 

运行结果:
//     0个参数传入
//     1个参数传入
//     多个参数传入,每个参数如下:
//     第1个参数是one;
//     第2个参数是two;
//     第3个参数是three;
//
//     多个参数传入,每个参数如下:
//     第1个参数是one;
//     第2个参数是two;
//     第3个参数是three;
//
//     0个Integer参数传入
//     1个Integer参数传入
//     多个参数传入,每个参数如下:
//     第1个Integer参数是1;
//     第2个Integer参数是2;
//     第3个Integer参数是3;
//
//     多个参数传入,每个参数如下:
//     第1个Integer参数是1;
//     第2个Integer参数是2;
//     第3个Integer参数是3;