Java Reference
In-Depth Information
You can write a loop to copy every element from the source array to the corresponding element
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, srcPos, targetArray, tarPos, length);
The parameters
srcPos
and
tarPos
indicate the starting positions in
sourceArray
and
targetArray
, respectively. The number of elements copied from
sourceArray
to
targ-
etArray
is indicated by
length
. For example, you can rewrite the loop using the following
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).
7.13
✓
✓
Use the
arraycopy
method to copy the following array to a target array
t
:
int
[] source = {
3
,
4
,
5
};
Check
Point
7.14
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++) {
System.out.print(array[i] +
" "
);
}
}
You can invoke it by passing an array. For example, the following statement invokes the
printArray
method to display
3
,
1
,
2
,
6
,
4
, and
2
.
printArray(
new int
[]{
3
,
1
,
2
,
6
,
4
,
2
});
Search WWH ::
Custom Search