Java Reference
In-Depth Information
Programming tip:
Procedure
arraycopy
in class
System
of package
java.lang
will copy an
array segment. To copy the
k
items in
b[i..i+k-
1
]
to
c[h..h+k-1],
use
System.arraycopy(b
,
i
,
c
,
h
,
k);
The copy works even if
b
and
c
refer to the same array object and the two seg-
ments overlap. See the API specification for details.
//
Process elements of
a1[0..a1.length-1]
, in order
//
inv:
0 ≤ i ≤ a1.length
and
a1[0..i-1] = a2[0..i-1]
for
(
int
i= 0; i != a1.length; i= i + 1) {
Process
a[i]
}
What does it mean to process an element
a1[i]
? Here, it means to return
false
if
a1[i]
is not equal to
a2[i]
.
Because the loop processes every element, if the loop terminates without
returning, return
true
at the end of the method.
This ends the development of the code. Fig. 8.3 contains the function.
8.3.6
Returning an array
Just as an array can be an argument of a method, it can be the result of a func-
tion. To indicate that the result is an array, just use the array type as the return
type. We illustrate this with a function that produces a copy of an array segment:
Activity
8-3.7
/** =
a copy of array segment
b[x..y] */
public static int
[] copy(
int
[] b,
int
x,
int
y)
How will the function be used?
We give examples when
d={3
,
5
,
2
,
7
,
3
,
8}
:
See lesson
page 8-3 to get
this program.
call
result
call range
result range
copy(d
,
0
,
2)
{3
,
5
,
2}
0..2
0..2
copy(d
,
1
,
4)
{5
,
2
,
7
,
3}
1..4
0..3
copy(d
,
2
,
5)
{2
,
7
,
3
,
8}
2..5
0..3
copy(d
,
2
,
1)
{}
2..1
0..-1
copy(d
,
i
,
j)
{...}
i..j
0..(j-i)
First, create a new array
result
in which to accumulate the result. Its size
is the size of the array segment to be copied:
int
[] result=
new int
[y+1-x];
We now have to write code to copy the elements of
b[x..y]
to
result[0..]
. We again use the loop schema from Sec. 8.3.2:
Search WWH ::
Custom Search