Java Reference
In-Depth Information
PITFALL:
(continued)
The equality operator
==
does not test two arrays to see if they contain the same val-
ues. 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 ==
even though
c
and
d
contain the same integers in the same indexed variables. A com-
parison using
==
will say they are not equal because
==
only checks the contents of the
array variables
c
and
d
, which are memory addresses, and
c
and
d
contain different
memory addresses.
If you want to test two arrays to see if they contain the same elements, then you can
define an
equalArrays
method for the arrays, just as you defined an
equals
method for
a class. Display 6.3 contains one possible definition of
equalArrays
for arrays in a small
demonstration class.
■
Self-Test Exercises
7. Consider the following class definition:
public class
SomeClass
{
public static void
doSomething(
int
n)
{
<Some code goes in here.>
}
<The rest of the definition is irrelevant to this question.>