Java Reference
In-Depth Information
Not just these types, but all of the Collections API and most of the other parts of the standard
Java API in 1.5 have been updated to be generic types. If you write your own multipurpose
classes, you can fairly easily change them to be generics in the same fashion.
The notation
<type>
is used to specify the particular type with which the class is to be in-
stantiated. Java developers had better get comfortable with this notation, because it is used
extensively in the 1.5 javadoc!
These additions related to data structuring are all covered in
Chapter 7
. Also see
Java Gener-
Variable argument lists
Java 5 introduced method declarations with variable-length argument lists, commonly called
“varargs.” This allows you to write a method that can be called with any number of argu-
ments of the given type. For example, a method
mySum
to be called with a variable number of
int
arguments can be written as:
static
static
int
int
mySum
(
int
int
...
args
) {
int
int
total
=
0
;
for
for
(
int
int
a
:
args
) {
total
+=
a
;
}
return
return
total
;
}
Note that there can only be one variable-length argument list in the parameter list of a meth-
od, and that it must be last; there can be other arguments before it, but not after.
Any of the following would be a valid call to this method:
System
.
out
.
println
(
mySum
(
5
,
7
,
9
));
System
.
out
.
println
(
mySum
(
5
));
System
.
out
.
println
(
mySum
());
int
int
[]
nums
= {
5
,
7
,
9
};
System
.
out
.
println
(
mySum
(
nums
));
That last one may be a bit surprising. When you think about it, the “…” in a method declara-
tion is a kind of syntactic sugar for “array of,” so you can pass an explicit array. This does
not mean that arrays and
…
are interchangeable; if you declare the method parameter as, say,