代码:
package test_demo;
/*
* 可变参数函数说明
* 传入指定数据类型的数组
* 优先匹配固定长度函数
* */
public class VarArgsDemo {
// 可变参数函数
public void printFn(String... args) {
for (String s : args) {
System.out.print(s + " ");
}
System.out.println();
}
// 优先匹配固定长度函数
public void printFn(String s) {
System.out.print("test!\n");
}
// 一个固定参数,其它可变参数函数
public void printMore(String str, String... args) {
System.out.println(str);
for (String s : args) {
System.out.print(s + " ");
}
System.out.println();
}
public static void main(String[] args) {
VarArgsDemo obj = new VarArgsDemo();
String str = "hello!";
String[] strs = {"hello!", "Good!", "what?"};
// 优先匹配固定长度函数
obj.printFn(str);
// 可变参数函数
obj.printFn("hello!", "Good!");
obj.printFn(strs);
// 一个固定参数,其它可变参数函数
obj.printMore("------", strs);
}
}
执行结果:
test!
hello! Good!
hello! Good! what?
------
hello! Good! what?