Methods and constructors that take a variable number of arguments
public static int max(int first, int … rest)
// note the last argument is typed , in C not (unsafe)
The “...� means zero or more arguments
Varargs are stored in an array
public static int max(int first, int... rest)
{
int max = first;
for(int next: rest)
{
if (next > max) max= next;
}
return max;
}
Notes:
Only the last argument can be a vararg
In APIs, sparingly
─ Only when the benefit is compelling
─ Don't overload a varargs method
• In clients, when the API supports them
─ reflection, message formatting, printf
Varargs automates and hides the process
─ Can retrofit existing APIs
─ Upward compatible with existing clients