Page 414 - Introduction to Programming with Java: A Problem Solving Approach
P. 414
380 Chapter 10 Arrays and ArrayLists
Your intent is to use January’s array as a starting point for the other month’s arrays. Specifically, you want to copy January’s prices into the other months’ arrays and modify the other months’ prices when neces- sary. The below statement creates the array for February’s prices. Note how pricesJanuary.length ensures that February’s array is the same length as January’s array.
double[] pricesFebruary = new double[pricesJanuary.length];
Suppose you want the values in February’s array to be the same as the values in January’s array except for the second entry, which you want to change from 9.99 to 10.99. In other words, you want something like this:
Output:
Jan Feb
1.29 1.29
9.99 10.99
22.50
22.50
4.55 4.55
7.35 7.35
6.49 6.49
To minimize re-entry effort and error, it would be nice to have the computer copy the first array’s values into the second array and then just alter the one element of the second array that needs changing. Would the following code fragment work?
Apago PDF Enhancer
pricesFebruary = pricesJanuary;
pricesFebruary[1] = 10.99;
An array name is just a reference. It contains the address of a place in memory where the array’s data be- gins.SopricesFebruary = pricesJanuary;getstheaddressofpricesJanuary’sdataand copies the address into pricesFebruary. Then pricesFebruary and pricesJanuary refer to the same physical data. This picture illustrates the point:
pricesJanuary
pricesFebruary
The problem with pricesFebruary and pricesJanuary referring to the same physical data is that if you change the data for one of the arrays, then you automatically change the data for the other array. For ex- ample,theabovepricesFebruary[1] = 10.99;statementupdatesnotonlypricesFebruary’s second element, but also pricesJanuary’s second element. And that’s not what you want.
Usually when you make a copy of an array, you’ll want the copy and the original to point to different array objects. To do that, assign array elements one at a time. See Figure 10.5’s ArrayCopy program. It uses a for loop to assign pricesJanuary elements to pricesFebruary elements one at a time.
Not a good idea.
array object
1.29
10.99
22.50
4.55
7.35
6.49