Programming and Problem Solving with Java

(やまだぃちぅ) #1
10.4 Examples of Declaring and Processing Arrays | 493

After the preceding deep copy code executes, what would be the result of each of the following
expressions?


numbers == sameNumbers


compareArrays(numbers, sameNumbers)


The first expression is false. The arrays contain the same values, but the equality test is for
addresses, not values. The second expression is true, because compareArraysis a method that
performs a deep comparison.


10.4 Examples of Declaring and Processing Arrays


We now look in detail at some specific examples of declaring and accessing arrays. These ex-
amples demonstrate different uses of arrays in applications.


Occupancy Rates


An application might use the following declarations to analyze occupancy rates in an apart-
ment building:


final intBUILDING_SIZE = 350; // Number of apartments


int[] occupants = new int[BUILDING_SIZE];
// occupants[aptNo] is the number of occupants in apartment aptNo
int totalOccupants; // Total number of occupants


Here occupantsis a 350-element array of integers (see Figure 10.7).occupants[0]= 3 if the first
apartment has three occupants; occupants[1]= 5 if the second apartment has five occu-
pants; and so on. If values have been stored into the array, then the following code totals the
number of occupants in the building:


totalOccupants = 0;
for (int aptNo = 0; aptNo < occupants.length; aptNo++)
totalOccupants = totalOccupants + occupants[aptNo];


The first time through the loop,counteris 0. We add the contents oftotalOccupants(that is, 0)
and the contents ofoccupants[0], storing the result intototalOccupants. Next,counterbecomes
1 and the loop test occurs. The second loop iteration adds the contents oftotalOccupantsand
the contents ofoccupants[1], storing the result intototalOccupants.Nowcounterbecomes 2 and
the loop test is made. Eventually, the loop adds the contents ofoccupants[349]to the sum and
incrementscounterto 350. At this point, the loop condition isfalse, and control exits the loop.
Note how we used the named constant BUILDING_SIZEin the array declaration and occu-
pants.lengthin the forloop. When we use a constant in this manner, it is easy to make
changes. If the number of apartments changes from 350 to 400, we just need to alter the
declaration of BUILDING_SIZE. We could also have written


for (int aptNo = 0; aptNo < BUILDING_SIZE; aptNo++)

Free download pdf