Java Reference
In-Depth Information
[0][1][2][3][4][5][6]
listA
5
10
15
20 25 30 35
[0][1][2][3][4][5][6]
listB
0
0
0
0
0
0
0
FIGURE 9-8
Arrays after the statement
listB = listA;
executes
Recall that this is called the shallow copying of data.
To copy the elements of
listA
into the corresponding elements of
listB
, you need to
provide an element-by-element copy, as shown by the following loop:
for
(
int
index = 0; index < listA.length; index++)
listB[index] = listA[index];
After this statement executes,
listA
and
listB
each refers to its own array and the
elements of
listA
are copied into the corresponding elements of
listB
(see Figure 9-9).
[0][1][2][3][4][5][6]
listA
5
10
15
20 25 30 35
[0][1][2][3][4][5][6]
listB
5
10
15
20 25 30 35
FIGURE 9-9
listA
and
listB
after the
for
loop executes
Recall that this is called the deep copying of data.
In addition to the assignment operator, you can use the relational operators
==
and
!=
to
compare arrays. However, you must be aware of what you are comparing. For example,
in the statement:
if
(listA == listB)
...
the expression
listA == listB
determines whether the values of
listA
and
listB
are
the same, and thus determines whether
listA
and
listB
refer to the same array. That is,
this statement does not determine whether
listA
and
listB
contain the same elements
(when
listA
and
listB
refer to arrays stored at different locations).
To determine whether
listA
and
listB
contain the same elements when they refer to
arrays stored at different locations, you need to compare them element by element. You
can, in fact, write a method that returns
true
if two
int
arrays contain the same
elements. For example, consider the following method:
Search WWH ::
Custom Search