Variable Arguments
November 16, 2010 Leave a comment
o Variable arguments, or varargs, allow a method to accept any number of arguments.
printNumberList(“Numbers”, 1, 2, 3); //method call
void printNumberList(String header, int… list) {
System.out.println(header);
for (int item : list) {
System.out.println(item);
}
}
o Only one vararg parameter is allowed per method.
o The vararg must be the last parameter.
o The vararg parameter is implemented as an array. Therefore, the compiler sees these methods declarations as equivalent:
void printNumberList(String header, int[] list);
void printNumberList(String header, int… list);
o Since the compiler implements variable arguments using arrays, the vararg can be treated as an array.
void printList(String header, int… list) {
System.out.println(header);
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
}