Java Reference
In-Depth Information
If you get past the
if
statement, you know that the arrays are of equal length.
Then you'll want to check whether they store the same sequence of values. Again,
test for inequality rather than equality, returning
false
if there's a difference:
public static boolean equals(int[] list1, int[] list2) {
if (list1.length != list2.length) {
return false;
}
for (int i = 0; i < list1.length; i++) {
if (list1[i] != list2[i]) {
return false;
}
}
...
}
If you get past the
for
loop, you'll know that the two arrays are of equal length and
that they store exactly the same sequence of values. In that case, you'll want to return the
value
true
to indicate that the arrays are equal. This addition completes the method:
public static boolean equals(int[] list1, int[] list2) {
if (list1.length != list2.length) {
return false;
}
for (int i = 0; i < list1.length; i++) {
if (list1[i] != list2[i]) {
return false;
}
}
return true;
}
This is a common pattern for a method like
equal
s: You test all of the ways that
the two objects might not be equal, returning
false
if you find any differences, and
returning
true
at the very end so that if all the tests are passed the two objects are
declared to be equal.
As a final example of common operations, let's consider the task of reversing the
order of the elements stored in an array. For example, suppose you have an array that
stores the following values:
[0]
[1]
[2]
[3]
[4]
[5]
list
3
8
7
-2
14
78
Search WWH ::
Custom Search