Java Reference
In-Depth Information
To continue with this example, let's define a method for the initializing code that
fills the array with odd numbers. We can accomplish this by moving the initializing
loop into a method that takes the array as a parameter:
public static void fillWithOdds(int[] data) {
for (int i = 0; i < data.length; i++) {
data[i] = 2 * i + 1;
}
}
We would then change our main method to call this fillWithOdds method:
int[] list = new int[5];
fillWithOdds(list);
incrementAll(list);
Like the incrementAll method, this method would change the array even
though it does not return it. But this isn't the best approach to use in this situation.
It seems odd that the fillWithOdds method requires you to construct an array
and pass it as a parameter. Why doesn't fillWithOdds construct the array itself?
That would simplify the call to the method, particularly if we ended up calling it
multiple times.
If fillWithOdds is going to construct the array, it will have to return a refer-
ence to it. Otherwise, only the method will have a reference to the newly con-
structed array. In its current form, the fillWithOdds method assumes that the
array has already been constructed, which is why we wrote the following two lines
of code in main :
int[] list = new int[5];
fillWithOdds(list);
If the method is going to construct the array, it doesn't have to be passed as a
parameter, but it will have to be returned by the method. Thus, we can rewrite these
two lines of code from main as a single line:
int[] list = fillWithOdds();
Now, however, we have a misleading method name. The method isn't just filling
an existing array, it is constructing one. Also notice that we can make the method
more flexible by telling it how large to make the array. So if we rename it and pass
the size as a parameter, then we'd call it this way:
int[] list = buildOddArray(5);
Search WWH ::




Custom Search