package pers.songhongkang.chaper3.day6;
//可变个数形参的方法:
/*1.格式:对于方法的形参:数据类型...形参名
* 2.可变个数的形参的方法与同名的方法之间构成重载
* 3.可变个数的形参在调用时,个数从0个开始,到无穷多个都可以。
* 4.使用可变个数形参的方法和使用数组的方法是一致的。
* 5.若方法中存在多个可变个数的形参,那个一定要声明在方法形参的最后;
* 6.在一个方法中,最多只能声明有一个可变个数的形参;
*
**/
public class TestArgs {
public static void main(String[] args) {
TestArgs t = new TestArgs();
t.sayHello("hefei", "suzhou", "shanghai");// 调用的是可变形参方法
t.sayHello("hefei");
t.sayHello(new String[] { "hello china", "hello beijing" });// 调用的是可变形参方法
t.sayHello(1, "aa", "bb", "cc");
}
// 如下四个方法构成重载
// 在类中一旦定义了重载的可变个数的形参的方法后,如下的两个方法可以省略
public void sayHello() {
System.out.println("hello world");
}
public void sayHello(String args) {
System.out.println("hello " + args);
}
// 可变个数形参的方法
public void sayHello(String... args) {
for (int i = 0; i < args.length; i++) {
System.out.print(args[i] + "\n");
}
}
public void sayHello(int i, String... args) {
System.out.print(i);
for (int j = 0; j < args.length; j++) {
System.out.print(args[j] + "\t");
}
}
public void sayHello1(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.print(args[i] + "\t");
}
}
// 以下举个例子:可变个数形参的使用
/*
* public int getSum(int i,int j){ return i+j; } public int getSum(int i,int
* j,int k){ return i+j+k; }
*/
// 等价于:
public int getSum(int... args) {
int sum = 0;
for (int i = 0; i < args.length; i++) {
sum += args[i];
}
return sum;
}
}
hefei
suzhou
shanghai
hello hefei
hello china
hello beijing
1aa bb cc