Sometimes you wish you could create methods with an arbitrary number of arguments. A classic example is a logging function which takes templates with an arbitrary number of placeholders:
logger.log("%s: %s" , "Input", "Hello world");
logger.log("%s: %s %s", "Input", "Hello", "world");
That shows log()
being called with 3 and 4 parameters, and you could support that by writing a number of versions:
void log(String pattern, String val1, String val2) { ... }
void log(String pattern, String val1, String val2, String val3) { ... }
... and in early versions of Java, people did that, but clearly you can't go on adding ever-longer versions, and at some point you'd say "OK, this is getting silly", and provide:
void log(String pattern, String[] values) { ... }
... to be called thus:
logger.log("%s: %s", new String[] { "Hello", "world" });
Varargs provides a syntax to let you allow the caller to supply as many arguments as they like.
void log(String pattern, String... values) {
// implementation sees values as a String[]
}
... and with this version, the caller doesn't need to explicitly create an array. It can be called with as many trailing arguments as you like:
logger.log("%s %s %s %s %s %s %s",
"The", "quality", "of", "mercy", "is", "not", "strained.");
I don't see any particular affinity between varargs and HTML field validation.