Java Reference
In-Depth Information
Figure 9.2
Output of the ArrayInitDemo program.
Copying Arrays
Because arrays are fixed in size, it is not unusual when working with arrays to
have to create a larger or smaller array and then copy the contents of an exist-
ing array into a new one. You can write a for loop that copies the contents of
one array to another. An alternative to a for loop is the static method array-
copy() in the System class.
The arraycopy() method has the following signature:
public static void arraycopy(Object source, int sourcePos,
Object destination, int destinationPos,
int length)
The arraycopy() method is a good example of using Object as a polymorphic
parameter. Because arrays are objects, they are of type Object. Therefore, any
array reference can be passed in to the source and destination parameters.
sourcePos indicates where in the source array to copy from, and destina-
tionPos indicates the location in the destination array to copy to. The length
parameter represents the number of elements to copy.
The ArrayCopyDemo program demonstrates the use of the arraycopy()
method by copying 10 ints from one array to another. Study the program and
try to determine its output, which is shown in Figure 9.3.
public class ArrayCopyDemo
{
public static void main(String [] args)
{
int [] odds = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
System.out.println(“** odds the first time **”);
for(int i = 0; i < odds.length; i++)
Search WWH ::




Custom Search