Java Reference
In-Depth Information
Display 6.8
String Processing Method with a Variable Number of Parameters
(part 2 of 2)
Sample Dialogue
What did you eat for dinner?
I ate salt cod, broccoli, french fries, salt peanuts, and apples.
You would be healthier if you could answer:
I ate cod, broccoli, peanuts, and apples.
can now fill the indexed variables of
a
in any order and need not fill the array starting
at the first element. This violates the spirit of the
private
modifier for the array
instance variable
a
. For this reason, the accessor method
getInsideArray
should
return
a
deep copy of the array named by the private instance variable
a
. A safe
definition of
getInsideArray
is the following:
public double
[] getInsideArray( )
// Good version
{
//Recall that maxNumberElements == a.length.
double
[] temp =
new double
[maxNumberElements];
for
(
int
i = 0; i < maxNumberElements; i++)
temp[i] = a[i];
return
temp;
}
If a private instance variable is an array type that has a class as its base type, then you
need to be sure to make copies of the class objects in the array when you make a copy
of the array. This is illustrated by the toy class in Display 6.9.
Display 6.9 also includes a copy constructor. As illustrated in that display, the copy
constructor should make a completely independent copy of the array instance variable
(that is, a deep copy) in the same way that the accessor method does. This same point is
also illustrated by the copy constructor in Display 6.5 .
Display 6.9
Accessor Method for an Array Instance Variable
(part 1 of 2)
1
/**
2
Demonstrates the correct way to define an accessor
3
method to a private array of class objects.
4
*/
5
public class
ToyExample
6 {
7
private
Date[] a;
The class
Date
is defined in Display 4.11, but
you do not need to know the details of the
definition to understand the point of this
example.