public class TestVarArgs {
static void printArray(Object... args) {
for (Object obj : args) {
System.out.print(obj + " ");
}
System.out.println();
}
}
第一次碰到上述代码觉得好奇怪,这三个点是什么东西。后来翻看《Thinking in java》,才知道这是可变参数,variable arguments,简称varargs。表示从0到任意个相同类型的参数,在编译期,这个可变参数将被转换为数组形式。
static void printArray(Object... args)
将转变成
static void printArray(Object[] args)
有几点需要注意:
1. 可变参数必须是在参数列表的最后一项
static void printArray(Object... args, int a)
这种形式将会报编译错误。
2. 可变参数方法可重载
static void printArray(String... args) {
}
static void printArray(int... args) {
}
可变参数与数组之间的区别:
可变参数可以用数组代替,但数组不能用可变参数代替
public class TestVarArgs {
static void printArray(Object... args) {
for (Object obj : args) {
System.out.print(obj + " ");
}
System.out.println();
}
public static void main(String[] argc) {
printArray(new Object[] { 1, 2, 3 });
}
}
可以编译成功,而如下形式无法编译通过
public class TestVarArgs {
static void printArray(Object[] args) {
for (Object obj : args) {
System.out.print(obj + " ");
}
System.out.println();
}
public static void main(String[] argc) {
printArray(1, 2, 3);
}
}
另外发现如下形式无法通过编译
public class TestVarArgs {
static void printArray(Object[] args) {
for (Object obj : args) {
System.out.print(obj + " ");
}
System.out.println();
}
static void printArray(Object... args) {
for (Object obj : args) {
System.out.print(obj + " ");
}
System.out.println();
}
}