Java Reference
In-Depth Information
Testing for Equality
Because arrays are objects, testing them for equality is more complex than testing
primitive values like integers and double s for equality. Two arrays are equivalent in
value if they have the same length and store the same sequence of values. The method
Arrays.equals performs this test:
if (Arrays.equals(list1, list2)) {
System.out.println("The arrays are equal");
}
Like the Arrays.toString method, often the Arrays.equal s method will be all
you need. But sometimes you'll want slight variations, so it's worth exploring how to
write the method yourself.
The method will take two arrays as parameters and will return a boolean result
indicating whether or not the two arrays are equal. So, the method will look like this:
public static boolean equals(int[] list1, int[] list2) {
...
}
When you sit down to write a method like this, you probably think in terms of
defining equality: “The two arrays are equal if their lengths are equal and they store
the same sequence of values.” But this isn't the easiest approach. For example, you
could begin by testing that the lengths are equal, but what would you do next?
public static boolean equals(int[] list1, int[] list2) {
if (list1.length == list2.length) {
// what do we do?
...
}
...
}
Methods like this one are generally easier to write if you think in terms of the
opposite condition: What would make the two arrays unequal? Instead of testing for
the lengths being equal, start by testing whether the lengths are unequal. In that case,
you know exactly what to do. If the lengths are not equal, the method should return a
value of false , and you'll know that the arrays are not equal to each other:
public static boolean equals(int[] list1, int[] list2) {
if (list1.length != list2.length) {
return false;
}
...
}
 
Search WWH ::




Custom Search