加上一个语法糖......所以它只是意味着它可以让你的代码更好。这是一个例子:
public class App {
public static void main(String[] args) {
Object obj = new Object();
String str = "test";
varArgsFoo(obj, str, 1); //Don't have to use an Array...
varArgsFoo(new Object[]{obj, str, 1}); //But you can if it suits you.
arrayFoo(new Object[]{obj, str, 1}); // Compiles, but you MUST pass in an Array.
arrayFoo(obj, str, 1); // Won't compile!!! Varargs won't work if an array is expected.
}
/**
* Can use simply a variable number of arguments, or an array whatever you like.
* @param obj
*/
static void varArgsFoo(Object... obj) {
for (int i = 0; i < obj.length; i++) {
System.out.println(obj[i]);
}
}
/**
* Must use an array, varargs (the ... notation) won't work.
*
* @param obj
*/
static void arrayFoo(Object[] obj) {
for (int i = 0; i < obj.length; i++) {
System.out.println(obj[i]);
}
}
}