Java中的可变参数使用语法及用途


一、什么时候使用可变参数?

如果方法中参数类型确定,但是"参数个数不确定"(需要很多方法重载) 时,可以使用可变参数




二、可变参数的格式

格式:
                     修饰符 返回值类型 方法名(参数类型 ... 形参名) {
                     }                     
范例:
                     public static void sum(int… a) {
                     }




代码演示

public class Test {
public static void main(String[] args) {
System.out.println(sum());
System.out.println(sum(1));
System.out.println(sum(2,5));
System.out.println(sum(1,2,3,4,5));
}

// public static int sum(int a,int b){
//
// return a+b;
// }
//
//
// public static int sum(int a,int b ,int c){
//
// return a+b+c;
// }

//当参数个数不确定时,可以把参数设计为可变参数
// int ... a 参数的数据是int , 参数的个数是任意的
//可变参数实际是数组, int... a,底层会转为 int[] a

public static int sum(int... a){
int sum=0;
for (int i = 0; i < a.length; i++) {
sum+=a[i];
}
return sum;
}

}





三、可变参数的注意事项

* 可变参数"本质是数组"

* 一个方法"只能有一个可变参数"

* 如果方法中有多个参数,"可变参数要放到最后"




案例1(多个可变参数)

public class Test2 {
public static void main(String[] args) {
}
public static void sum(int ... a,double ...b){
} //报错
}





案例2(可变参数不在末尾)

public class Test2 {
public static void main(String[] args) {
}
public static void sum(int ... a,int b){
} //报错
}





作者:今日头条 KJ丶JK /CSDN-KJ.JK

展开阅读全文

页面更新:2024-04-16

标签:参数   法名   末尾   数组   范例   语法   个数   用途   案例   类型   格式   方法

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top