Java Reference
In-Depth Information
PITFALL: Arrays with a Class Base Type
The base type of an array can be of any type, including a class type. For example, sup-
pose
Date
is a class and consider the following:
Date[] holidayList =
new
Date[20];
This creates the 20 indexed variables
holidayList[0]
,
holidayList[1]
, ...,
holidayList[19]
. It is important to note that this creates 20 indexed variables of type
Date
. This does not create 20 objects of type
Date
. (The index variables are automat-
ically initialized to
null
, not to an object of the class
Date
.) Like any other variable of
type
Date
, the indexed variables require an invocation of a constructor using
new
to
create an object. One way to complete the initialization of the array
holidayList
is
as follows:
Date[] holidayList =
new
Date[20];
for
(
int
i = 0; i < holidayList.length; i++)
holidayList[i] =
new
Date();
If you omit the
for
loop (and do not do something else more or less equivalent), then
when you run your code, you will undoubtedly get an error message indicating a “null
pointer exception.” If you do not use
new
to create an object, an indexed variable like
holidayList[i]
is just a variable that names no object and hence cannot be used as
the calling object for any method. Whenever you are using an array with a class base
type and you get an error message referring to a “null pointer exception,” it is likely
that your indexed variables do not name any objects and you need to add something
like the above
for
loop.
■
Array Parameters
You can use both array indexed variables and entire arrays as arguments to methods,
although they are different types of parameters. We first discuss array indexed variables
as arguments to methods.
An indexed variable can be an argument to a method in exactly the same way that
any variable of the array base type can be an argument. For example, suppose a pro-
gram contains the following declarations:
indexed
variable
arguments
double
n = 0;
double
[] a =
new double
[10];
int
i;
If
myMethod
takes one argument of type
double
, then the following is legal:
myMethod(n);