Var Args

Some methods can take any number of a given type of parameter. A simple solution is to always pass a collection as the parameter. Callers of such methods, however, are cluttered by the presence of the intermediate collections:

Collection<String> keys = new ArrayList<String>();
keys.add(key1);
keys.add(key2);
object.index(keys);

This problem is common enough that Java provides a mechanism to pass a variable number of arguments to a method. By declaring the method above as method(Class... classes), the client can invoke the method with any number of arguments:

object.index(key1, key2);

Var args must be the last parameter. If a method has var args and optional arguments as described above, the optional arguments have to go before the var args.

Implementation Patterns

contents