Programming and Problem Solving with Java

(やまだぃちぅ) #1
10.7 S pecial Kinds of Array Processing | 501

What does sumSalesreceive as an argument? The base address of gourmetBurgers(the arrow
in Figure 10.8).
We must consider two cases when passing array components as arguments to a method:
(1) the component is of a primitive type or (2) the component is of a reference type. If the com-
ponent is of a primitive type, the method cannot change the value of its argument. If the com-
ponent is of a reference type, and the method changes its parameter, there are two
possibilities. Assigning a new value to the parameter causes it to refer to a different object
and doesn’t affect the argument. Changing the parameter with a transformer method has
the side effect of changing the argument and is considered poor programming style. Recall
our house analogy: Are you just looking at the house, or are you going inside?


10.7 Special Kinds of Array Processing


Two types of problems occur frequently that use arrays. One type of problem uses only part
of the defined array to store data. In the other, the index values have specific meaning within
the problem.


Partial (or Sub) Array Processing


The size of an array is the declared number of array components—the number of slots set aside
for the array object in memory. Java has an instance variablelengthassociated with each array
object that contains this value. In many problems, however, we do not know the number of
data values, so we declare the array to be as big as it would ever need to be. As a consequence,
we may not fill all of the array components with values.To avoid processing slots into which we
have not stored valid data, we must keep track of how many components are actually filled.
As we put values into the array, we keep a count of how many components are filled. We then
use this count to process only those components that contain valid values.The remaining places
are not processed. For example, if there are 250 students in a class, an application to analyze test
grades would set aside 250 locations for the grades. However, some students may be absent on
the day of the test. We must therefore count the number of test grades and use that number, rather
than 250, to control the processing of the array. This number becomes part of the internal rep-
resentation of the class being defined. Figure 10.10 visualizes this type of processing.


Indexes with Semantic Content


In some problems, an array index has meaning beyond a simple position; that is, the index
has semantic content. An example is the gourmetBurgersarray discussed earlier. This array
was indexed by the number of the type of hamburger minus one. That is, the sales for the
hamburger that the company called #1 occupied the 0 position in the array; hamburger #2
occupied position 1 in the array; and so on.

Free download pdf