Java Reference
In-Depth Information
There are three ways to copy arrays:
■
Use a loop to copy individual elements one by one.
■
Use the static
arraycopy
method in the
System
class.
■
Use the
clone
method to copy arrays; this will be introduced in Chapter 15,
Abstract Classes and Interfaces.
You can write a loop to copy every element from the source array to the corresponding ele-
ment in the target array. The following code, for instance, copies
sourceArray
to
targetArray
using a
for
loop.
int
[] sourceArray = {
2
,
3
,
1
,
5
,
10
};
int
[] targetArray =
new int
[sourceArray.length];
for
(
int
i =
0
; i < sourceArray.length; i++) {
targetArray[i] = sourceArray[i];
}
Another approach is to use the
arraycopy
method in the
java.lang.System
class to copy
arrays instead of using a loop. The syntax for
arraycopy
is:
arraycopy
method
arraycopy(sourceArray, src_pos, targetArray, tar_pos, length);
The parameters
src_pos
and
tar_pos
indicate the starting positions in
sourceArray
and
targetArray
, respectively. The number of elements copied from
sourceArray
to
targetArray
is indicated by
length
. For example, you can rewrite the loop using the fol-
lowing statement:
System.arraycopy(sourceArray,
0
, targetArray,
0
, sourceArray.length);
The
arraycopy
method does not allocate memory space for the target array. The target array
must have already been created with its memory space allocated. After the copying takes place,
targetArray
and
sourceArray
have the same content but independent memory locations.
Note
The
arraycopy
method violates the Java naming convention. By convention, this
method should be named
arrayCopy
(i.e., with an uppercase C).
6.12
✓
✓
Use the
arraycopy()
method to copy the following array to a target array
t
:
Check
Point
int
[] source = {
3
,
4
,
5
};
6.13
Once an array is created, its size cannot be changed. Does the following code resize
the array?
int
[] myList;
myList =
new int
[
10
];
// Sometime later you want to assign a new array to myList
myList =
new int
[
20
];
When passing an array to a method, the reference of the array is passed to the method.
Key
Point
Just as you can pass primitive type values to methods, you can also pass arrays to methods.
For example, the following method displays the elements in an
int
array:
public static void
printArray(
int
[] array) {
for
(
int
i =
0
; i < array.length; i++) {