Java中可变参数的语法和用途是什么?
- 内容介绍
- 文章标签
- 相关推荐
本文共计621个文字,预计阅读时间需要3分钟。
(目录)+ 一、何时使用可变参数?+ 如果方法中参数类型已确定,但参数个数不确定(需要很多方法重载),此时,可以使用可变参数+ 二、可变参数的格式:+ 格式:修饰符 返回值类型 方法名(修饰符 返回值类型, 参数名1, 参数名2, ...)+ 例如:修饰符 返回值类型 方法名(修饰符 返回值类型, 参数名1, 参数名2, ...)+ 修饰符:public、protected、private、static、final等+ 返回值类型:方法返回值的类型+ 方法名:方法名称+ 参数名1、参数名2:参数名称+ ...:表示可以有多个参数
(目录)
`
一、什么时候使用可变参数?
如果方法中参数类型确定,但是"参数个数不确定"(需要很多方法重载) 时,可以使用可变参数
二、可变参数的格式
格式:
修饰符 返回值类型 方法名(参数类型 ... 形参名) {
}
范例:
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
本文共计621个文字,预计阅读时间需要3分钟。
(目录)+ 一、何时使用可变参数?+ 如果方法中参数类型已确定,但参数个数不确定(需要很多方法重载),此时,可以使用可变参数+ 二、可变参数的格式:+ 格式:修饰符 返回值类型 方法名(修饰符 返回值类型, 参数名1, 参数名2, ...)+ 例如:修饰符 返回值类型 方法名(修饰符 返回值类型, 参数名1, 参数名2, ...)+ 修饰符:public、protected、private、static、final等+ 返回值类型:方法返回值的类型+ 方法名:方法名称+ 参数名1、参数名2:参数名称+ ...:表示可以有多个参数
(目录)
`
一、什么时候使用可变参数?
如果方法中参数类型确定,但是"参数个数不确定"(需要很多方法重载) 时,可以使用可变参数
二、可变参数的格式
格式:
修饰符 返回值类型 方法名(参数类型 ... 形参名) {
}
范例:
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){
} //报错
}

