2020-01-16 19:10:05:226 星期四☁
[可变长参数,就是无限传参数个数]
先说注意点:
1、写法:方法名称(类型…命名)。
2、传入的参数为数组类型。
3、当传多参,一个方法只能有一个多参,并且保证的最后一位。
看以下场景:
/**
* 场景一:
* 方法的重载,根据参数不同
*/
private static int addParams(int a, int b) throws Exception {
return a + b;
}
private static int addParams(int a, int b, int c) throws Exception {
return a + b + c;
}
private static int addParams(int a, int b, int c, int d) throws Exception {
return a + b + c + d;
}
如果我们有5、6、7个参数?以及更多,我们还要继续重载上面的方法吗?
显示不是,看改进。
/**
* 改进:
* 如何用多参改进?
*/
private static int addParams(int... a) throws Exception {
int result = 0;
for (int i : a) {
result += i;
}
return result;
}
//测试调用端
public static void main(String[] args) {
try {
//第一种调用方法
int[] a = {5, 6, 7, 8};
int addParams = addParams(a);
//第二种{这里有补充,在下面}
addParams(5, 6, 7, 8);
System.out.println(addParams);
} catch (Exception e) {
e.printStackTrace();
}
}
以上为简单demo,用法如此,牢记注意事项。
补充:[也很重要]
当存在无限参数,与有限参数同名的方法时如:
addParams(5, 6, 7, 8);
他调用的是?无限参数方法,还是有限参数方法???呢
结论,调用的是有限参数方法。而不调用无限参数!!!
论证可以自己验证,这里不做验证。
完结,记不住的东西,就背背,刻在骨髓里,与血肉融合,变为你的东西。
因篇幅问题不能全部显示,请点此查看更多更全内容