Datasheet
The introduction of this interface prevents dependency on the java.util interfaces. The change in the
for loop syntax is at the language level and it makes sense to ensure that any support needed in the
class library is located in the
java.lang branch.
Variable Arguments
C and C++ are a couple of the languages that support variable length argument lists for functions. Java
decided to introduce this aspect into the language. Only use variable argument parameter lists in cases
that make sense. If you abuse them, it’s easy to create source code that is confusing. The C language uses
the ellipsis (three periods) in the function declaration to stand for “an arbitrary number of parameters,
zero or more.” Java also uses the ellipsis but combines it with a type and identifier. The type can be
anything — any class, any primitive type, even array types. When using it in an array, however, the ellip-
sis must come last in the type description, after the square brackets. Because of the nature of variable
arguments, each method can only have a single type as a variable argument and it must come last in the
parameter list.
Following is an example of a method that takes an arbitrary number of primitive integers and returns
their sum:
public int sum(int... intList)
{
int i, sum;
sum=0;
for(i=0; i<intList.length; i++) {
sum += intList[i];
}
return(sum);
}
All arguments passed in from the position of the argument marked as variable and beyond are combined
into an array. This makes it simple to test how many arguments were passed in. All that is needed is to ref-
erence the
length property on the array, and the array also provides easy access to each argument.
Here’s a full sample program that adds up all the values in an arbitrary number of arrays:
public class VarArgsExample {
int sumArrays(int[]... intArrays)
{
int sum, i, j;
sum=0;
for(i=0; i<intArrays.length; i++) {
for(j=0; j<intArrays[i].length; j++) {
sum += intArrays[i][j];
}
}
return(sum);
18
Part I: Thinking Like a Java Developer
05_777106 ch01.qxp 11/28/06 10:43 PM Page 18