Java里面的可变长参数是指在方法定义中可以使用个数不确定的参数,对于同一方法可以使用不同个数的参数调用,变长参数只是语法糖,其本质上还是将变长的实际参数 varargs 包装为一个数组。例如:
print("hello");
print("hello" + "world");
print("hello" + "zeorods" + "world");
1.定义:
Java里面使用…表示可变长参数,置于参数类型和形式参数中间, 且方法可以把参数当成数组进行遍历, 只能放在参数表的结尾:
print(String... args){
for(String temp : args) {
System.out.println(temp);
}
}
2.含可变长参数方法的调用
调用的时候可以给出任意多个参数(包含空参),例如:
print();
print("hello");
print("hello","lisi");
print("hello","张三", "alexia")
3.可变长参数的使用规则
3.1 在调用方法的时候,优先选择固定参数的方法,看下面代码的输出:
public class VarArgsTest {
public void print(String... args) {
System.out.println("many args: ");
for (int i = 0; i < args.length; i++) {
System.out.println("the " + i + "th: " + args[i]);
}
}
public void print(String arg) {
System.out.print("only one arg: " + arg + "\n");
}
public static void main(String[] args) {
VarArgsTest test = new VarArgsTest();
test.print("hello");
test.print("hello", "alexia");
}
}
result:
only one arg: hello
many args:
the 0th: hello
the 1th: alexia
3.2 如果要调用的方法可以和两个可变参数匹配,则出现编译错误。
void print(String... args);
void print(String test, String... args);
3.3 一个方法只能有一个可变长参数,并且这个可变长参数必须是该方法的最后一个参数
以下两种方法定义都是错误的。
public void test(String... strings, ArrayList list);
public void test(String... strings, ArrayList... list);
4.可变长参数的使用规范
4.1 避免带有可变长参数的方法重载:如3.1中,编译器虽然知道怎么调用,但人容易陷入调用的陷阱及误区
4.2 别让null值和空值威胁到变长参数方法,如3.2中所示,为了说明null值的调用,重新给出一个例子:
package com;public class VarArgsTest1 {
public void print(String test, Integer... is) {
}
public void print(String test,String...args ){
}
public static void main(String[] args) {
VarArgsTest1 test = new VarArgsTest1();
test.print("hello");
test.print("hello", null);
}
}
这时会发现两个调用编译都不通过:因为两个方法都匹配,编译器不知道选哪个,于是报错了,这里同时还有个非常不好的编码习惯,即调用者隐藏了实参类型,这是非常危险的,不仅仅调用者需要“猜测”该调用哪个方法,而且被调用者也可能产生内部逻辑混乱的情况。对于本例来说应该做如下修改:
public static void main(String[] args) {
VarArgsTest1 test = new VarArgsTest1();
String[] strs = null;
test.print("hello", strs);
}