Java Reference
In-Depth Information
8.3.5
Checking equality of arrays
Suppose
a1
and
a2
are of type
int
[]
. They contain the names of array objects
(and not the arrays themselves), so
a1 == a2
tests whether
a1
,
a2
contain the
same name rather than whether the array contents are equal. We write a method
to compare the contents:
Activity
8-3.6
/** = "
arrays
a1
and
a2
are equal
" */
public static boolean
equals(
int
[] a1,
int
[] a2)
The method is a function, and it returns
true
if the arrays are equal and
false
otherwise. The arrays are equal if (1) the parameters have exactly the same
value or (2) the array objects have the same length and their corresponding ele-
ments are equal.
If
a1
and
a2
both are
null
, or if they contain the same array name, the func-
tion returns
true
. (In many situations, a method may require its array parameters
to be not
null
. Here, it makes sense to allow
null
array arguments.)
If one of
a1
and
a2
contains
null
but the other does not, the arrays are not
equal, so the function returns
false
.
If
a1
and
a2
have different lengths, the function returns
false
.
At this point, the arrays have the same length, so their elements have to be
compared for equality. We use the loop schema from Sec. 8.3.2:
See lesson
page 8-3 to get
this program.
//
Process elements of
c[h..k-1]
, in order
//
inv:
h≤i≤k
and
c[h..i-1]
has been processed
for
(
int
i= h; i != k; i= i + 1)
{
Process
c[i] }
Instead of array
c
,
we have
a1
; instead of
h
, we have
0
; and instead of
k
we have
a1.length
. We also update the invariant.
Activity 8-3.5
shows you how
to test it.
/** = "
arrays
a1
and
a2
are equal
" */
public static
boolean equals(
int
[] a1,
int
[] a2) {
if
(a1 == a2) {
return true
; }
if
(a1 ==
null
|| a2 ==
null
) {
return false
; }
if
(a1.length != a2.length) {
return false
; }
//
Return false if
a1[i] != a2[i]
for some
i
.
//
inv:
0 ≤ i ≤ a1.length
and
a1[0..i-1] = a2[0..i-1]
for
(
int
i= 0; i != a1.length; i= i + 1) {
if
(a1[i] != a2[i])
{
return false
; }
}
return true
;
}
Figure 8.3:
Function
equals
, to check the equality of arrays
Search WWH ::
Custom Search