Java Reference
In-Depth Information
PITFALL: (continued)
The assignment statement b = a; copies the memory address from a to b so that the
array variable b contains the same memory address as the array variable a . After the
assignment statement, a and b are two different names for the same array. Thus, when
we change the value of a[2] , we are also changing the value of b[2] .
Unless you want two array variables to be two names for the same array (and on
rare occasions, you do want this), you should not use the assignment operator with
arrays. If you want the arrays a and b in the preceding code to be different arrays with
the same values in each index position, then instead of the assignment statement
b = a;
you need to use something such as the following:
int i;
for (i = 0; (i < a.length) && (i < b.length); i++)
b[i] = a[i];
Note that the above code will not make b an exact copy of a , unless a and b have the
same length.
The equality operator == does not test two arrays to see if they contain the same
values. It tests two arrays to see if they are stored in the same location in the computer's
memory. For example, consider the following code:
==
with arrays
int [] c = new int [10];
int [] d = new int [10];
int i;
for (i = 0; i < c.length; i++)
c[i] = i;
for (i = 0; i < d.length; i++)
d[i] = i;
if (c == d)
System.out.println("c and d are equal by ==.");
else
System.out.println("c and d are not equal by ==.");
This produces the output
c and d are not equal by ==
(continued)
 
Search WWH ::




Custom Search