Java Reference
In-Depth Information
JDK 5 allows us to specify that there will be a variable number of arguments of the same
type passed to the method or constructor. So you could specify that the exact number of
String s passed to the constructor is variable by specifying a constructor of
Dog(int age, String... args) {
for (String parameter : args) {
System.out.println("Received parameter " + parameter);
}
}
As you can see in the previous code, the ellipsis ( ... ) immediately follows the type it
refers to. Once it's inside the body of your method, you can just treat the argument as an array
of the named type.
Note You can only have one variable argument list in a given method or constructor declaration,
and it must be the last parameter in the method or constructor. For example, you cannot have
Dog(int... ages, String name) .
Caution Be very careful when overloading constructors or methods with versions containing VarArgs.
It is very easy to end up with overridden methods that cannot be differentiated by the compiler (e.g.,
Dog(String name, String... args) and Dog(String... args) are effectively the same), or end up
with a generic method that matches more than you bargained for (e.g., Dog(Object... args) will match
all constructors, due to autoboxing).
You may have realized that a similar effect was possible under earlier versions of the JDK:
namely, you simply passed an array of the named type into your method. However, to use this,
you effectively had to create a new array. For example:
public static void lookupDog(String... searchCriteria) {
for (String criterion : searchCriteria) {
// do work here
}
}
public static void lookupCat(String[] searchCriteria) {
for (String criterion : searchCriteria) {
// do work here - no different than working with Dog method
}
}
public static void main(String[] args) {
// first the easy code: use the Dog method:
lookupDog("Breed", "Terrier", "Color", "Brown");
Search WWH ::




Custom Search