Checking whether two arrays contain a mismatch

If two arrays are equal, then a mismatch should return -1. But if two arrays are not equal, then a mismatch should return the index of the first mismatch between the two given arrays. In order to resolve this problem, we can rely on JDK 9 Arrays.mismatch() methods.

For example, we can check for mismatches between integers1 and integers2 as follows:

int mi12 = Arrays.mismatch(integers1, integers2); // -1

The result is -1, since integers1 and integers2 are equal. But if we check for integers1 and integers3, we receive the value 5, which is the index of the first mismatch between these two:

int mi13 = Arrays.mismatch(integers1, integers3); // 5
If the given arrays have different lengths and the smaller one is a prefix for the larger one, then the returned mismatch is the length of the smaller array.

For arrays of Object, there are dedicated mismatch() methods as well. These methods count on the equals() contract or on the given Comparator. We can check whether there is a mismatch between melons1 and melons2 as follows:

int mm12 = Arrays.mismatch(melons1, melons2); // -1

If the mismatch occurs on the first index, then the returned value is 0. This is happening in the case of melons1 and melons3:

int mm13 = Arrays.mismatch(melons1, melons3); // 0

As in the case of Arrays.equals(), we can check mismatches in an explicit range using a Comparator:

// range [1, 2), return -1
int mms13 = Arrays.mismatch(melons1, 1, 2, melons3, 1, 2);

// Comparator by melon's weights, return -1
int mmw13 = Arrays.mismatch(melons1, melons3, byWeight);

// Comparator by melon's types, return 0
int mmt13 = Arrays.mismatch(melons1, melons3, byType);

// range [1,2) and Comparator by melon's types, return -1
int mmrt13 = Arrays.mismatch(melons1, 1, 2, melons3, 1, 2, byType);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset