Page 415 - Introduction to Programming with Java: A Problem Solving Approach
P. 415

                10.5 Copying an Array 381
 /*******************************************************************
*
ArrayCopy.java
Dean & Dean
This copies an array and then alters the copy.
********************************************************************/
*
*
*
public class ArrayCopy
{
}
// end class ArrayCopy
public static void main(String[] args)
{
}
// end main
double[] pricesJanuary =
{1.29, 9.99, 22.50, 4.55, 7.35, 6.49};
double[] pricesFebruary = new double[pricesJanuary.length];
for (int i=0; i<pricesJanuary.length; i++)
{
}
{
}
pricesFebruary[i] = pricesJanuary[i];
pricesFebruary[1] = 10.99;
System.out.printf("%7s%7s\n", "Jan", "Feb");
for (int i=0; i<pricesJanuary.length; i++)
System.out.printf("%7.2f%7.2f\n",
     Apago PDF Enhancer
pricesJanuary[i], pricesFebruary[i]);
Figure 10.5 ArrayCopy program that copies an array and then alters the copy This is what the code in Figure 10.5 produces:
      pricesJanuary
System.arraycopy
pricesFebruary
1.29
9.99
22.50
4.55
7.35
6.49
Copying data from one array to another is a very common operation, so Java designers provide a spe- cial method, System.arraycopy, just for that purpose. It allows you to copy any number of elements from any place in one array to any place in another array. Here’s how you could use it, copy Figure 10.5’s pricesJanuary array to the pricesFebruary array:
System.arraycopy(pricesJanuary, 0, pricesFebruary, 0, 6);
pricesFebruary[1] = 10.99;
The first argument is the source array name, that is, the name of the array you’re copying from. The second argument is the index of the source array’s first element to copy. The third argument is the destination array
1.29
10.99
22.50
4.55
7.35
6.49














































   413   414   415   416   417