Arrays mismatch() Method in Java – Java 中的数组不匹配()方法

最后修改: 2023年 10月 26日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll understand the behavior of the Arrays mismatch() method. This method has three principal overloads, each available with a set of types. We’ll stick to int arrays for our examples.

在本教程中,我们将了解 Arrays mismatch() 方法的行为。该方法有三个主要重载,每个重载都有一组类型。我们将在示例中使用 int 数组。

2. The Base mismatch() Method

2.基本不匹配()方法

Let’s start with the simplest version of the mismatch() method.

让我们从最简单的 mismatch() 方法开始。

2.1. Length of the Common Prefix

2.1.通用前缀的长度

The mismatch() method takes two arrays and returns the index of the first different item between the arrays. For instance, {1, 2, 3, 4, 5} and {1, 2, 3, 5, 8} differ on index 3.

mismatch()方法接收两个数组,并返回两个数组之间第一个不同项的索引。例如,{1, 2, 3, 4, 5}{1, 2, 3, 5, 8} 在索引 3 上不同。

Let’s use JUnit5 to write a unit test to verify the method behaves as expected:

让我们使用JUnit5编写一个单元测试来验证方法是否符合预期:

@Test
void givenTwoArraysWithACommonPrefix_whenMismatch_thenIndexOfFirstMismatch() {
    int[] firstArray = {1, 2, 3, 4, 5};
    int[] secondArray = {1, 2, 3, 5, 8};
    assertEquals(3, Arrays.mismatch(firstArray, secondArray));
}

We can notice that if one array is a prefix of the other, the result is the length of the smallest array:

我们可以注意到,如果一个数组是另一个数组的前缀,结果就是最小数组的长度:

@Test
void givenFirstArrayIsAPrefixOfTheSecond_whenMismatch_thenFirstArrayLength() {
    int[] firstArray = {1, 2, 3, 4, 5};
    int[] secondArray = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    assertEquals(firstArray.length, Arrays.mismatch(firstArray, secondArray));
}

If the first element of the two arrays is different, the result is 0:

如果两个数组的第一个元素不同,则结果为0

@Test
void givenNoCommonPrefix_whenMismatch_thenZero() {
    int[] firstArray = {1, 2, 3, 4, 5};
    int[] secondArray = {9, 8, 7};
    assertEquals(0, Arrays.mismatch(firstArray, secondArray));
}

2.2. Edge Cases

2.2.边缘案例

When the two arrays have the same elements in the same order, the method returns -1:

当两个数组的元素顺序相同时,该方法返回 -1

@Test
void givenTwoEmptyArrays_whenMismatch_thenMinusOne() {
    assertEquals(-1, Arrays.mismatch(new int[] {}, new int[] {}));
}

Let’s note that two empty arrays have no mismatch, so the result is also -1 in this case:

请注意,两个空数组没有错配,因此在这种情况下,结果也是 -1

@Test
void givenTwoEmptyArrays_whenMismatch_thenMinusOne() {
    assertEquals(-1, Arrays.mismatch(new int[] {}, new int[] {}));
}

2.3. Null or Empty Array

2.3.空或空数组

However, if exactly one of the two arrays is empty, mismatch() returns the length of the empty array, i.e., 0:

但是,如果两个数组中正好有一个为空,mismatch() 将返回空数组的长度,即 0

@Test
void givenExactlyOneAnEmptyArray_whenMismatch_thenZero() {
    int[] firstArray = {};
    int[] secondArray = {1, 2, 3};
    assertEquals(0, Arrays.mismatch(firstArray, secondArray));
}

Last but not least, mismatch() throws a NullPointerException if any of the two arrays is null:

最后但并非最不重要的一点是,mismatch() 如果两个数组中的任何一个为 NullPointerException 则会抛出 null: 异常。

@Test
void givenAtLeastANullArray_whenMismatch_thenThrowsNullPointerException() {
    int[] firstArray = null;
    int[] secondArray = {1, 2, 3, 4, 5};
    assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, secondArray));
}

Finally, we can apply the mismatch() method to boolean, byte, char, short, int, long, float, double and Object arrays.

最后,我们可以将 mismatch() 方法应用于 boolean, byte, char, short, int, long, float, doubleObject 数组。

3. mismatch() With Subarrays

3.mismatch() 使用子数组

We’ll now focus on the method whose signature is, in the case of int arrays: int mismatch(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex). This method variant extracts a subarray from each array then checks for mismatches.

现在,我们将重点关注其签名为int数组的方法:int mismatch(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)此方法变体从每个数组中提取一个子数组,然后检查是否存在错配。

3.1. Similar Behavior on Subarrays

3.1.子阵列上的类似行为

Let’s see its behavior on an example:

让我们在一个例子中看看它的行为:

@Test
void givenTwoSubArraysWithACommonPrefix_whenMismatch_thenIndexOfFirstMismatch() {
    int[] firstArray = {1, 2, 3, 4, 5};
    int[] secondArray = {0, 1, 2, 3, 5, 8};
    assertEquals(3, Arrays.mismatch(firstArray, 0, 4, secondArray, 1, 6));
}

Let’s understand what happens step by step:

让我们一步步了解发生了什么:

  • first, the method computes the subarray between indexes 0 and 4 of the original first array {1, 2, 3, 4, 5}: the result is the new first array {1, 2, 3, 4}
  • it then calculates the subarray between indexes 1 and 6 of the original second array {0, 1, 2, 3, 5, 8}: the result is the array {1, 2, 3, 5, 8}
  • eventually, it applies the base mismatch() method to the two subarrays: {1, 2, 3, 4} and {1, 2, 3, 5, 8}; both start with {1, 2, 3} in that order, but the mismatch is on their 4th element

As a result, the method returns 4 in this case. Furthermore, all the points listed in the base version are valid for these variants:

因此,该方法在这种情况下会返回 4 。此外,基本版本中列出的所有要点对这些变体都有效:

  • if there is no mismatch, the method returns -1
  • if any array is null, the method throws a NullPointerException
  • this method is overriden with boolean, byte, char, short, int, long, float, double and Object arrays

3.2. Additional Exceptions

3.2.其他例外情况

In addition to the standard behavior, the subarray method introduces new Exceptions. If, for any array, the “from” index is greater than the “to” index, mismatch() throws an IllegalArgumentException:

除了标准行为外,subarray 方法还引入了新的 异常如果对于任何数组,”from “索引大于 “to “索引,mismatch()将抛出 IllegalArgumentException: 异常。

@Test
void givenToIndexGreaterThanFromIndex_whenMismatch_thenThrowsIllegalArgumentException() {
    int[] firstArray = {2, 3, 4, 5, 4, 3, 2};
    int[] secondArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    assertThrows(IllegalArgumentException.class, () -> Arrays.mismatch(firstArray, 4, 2, secondArray, 0, 6));
}

Besides, if we pass an illegal index as an argument, the method throws an ArrayIndexOutOfBoundsException:

此外,如果我们将非法索引作为参数传递,该方法将抛出 ArrayIndexOutOfBoundsException 异常:

@Test
void givenIllegalIndexes_whenMismatch_thenThrowsArrayIndexOutOfBoundsException() {
    int[] firstArray = {2, 3, 4, 5, 4, 3, 2};
    int[] secondArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, -1, 2, secondArray, 0, 6));
}

To sum up, the “from” index must be greater than 0, and the “to” index must be greater than the “from” index and lower than the arrays’ length.

总之,”from “索引必须大于 0,而 “to “索引必须大于 “from “索引且小于数组的长度。

4. Generic Method With Comparator

4.带比较器的通用方法

The last variant of the method takes two arrays of a generic type and computes the first mismatch given a Comparator. For instance, let’s take two String arrays and use the CASE_INSENSITIVE_ORDER Comparator from the String class:

该方法的最后一个变体使用两个通用类型的数组,并在给定比较器的情况下计算第一个不匹配数组。例如,让我们使用两个 String 数组,并使用 String 类中的 CASE_INSENSITIVE_ORDER 比较器

@Test
void givenTwoStringArraysAndAComparator_whenMismatch_thenIndexOfFirstMismatch() {
    String[] firstArray = {"one", "two", "three"};
    String[] secondArray = {"ONE", "TWO", "FOUR"};
    Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
    assertEquals(2, Arrays.mismatch(firstArray, secondArray, comparator));
}

All the points from the previous sections regarding edge cases and Exceptions are valid again. Furthermore, if the given Comparator is null, a NullPointerException is thrown as well:

前几节中有关边缘情况和异常的所有观点都是正确的。此外,如果给定的 Comparator,也会抛出 NullPointerException 异常:

@Test
void givenAtLeastANullArrayOrNullComparator_whenMismatch_thenThrowsNullPointerException() {
    String[] firstArray = {"one"};
    String[] secondArray = {"one"};
    Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
    assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, secondArray, null));
}

Lastly, we can note that there is also an overridden method that works similarly with subarrays:

最后,我们可以注意到,还有一种重载方法也可以类似地处理子数组:

@Test
void givenTwoStringSubarraysAndAComparator_whenMismatch_thenIndexOfFirstMismatch() {
    String[] firstArray = {"one", "two", "three", "four"};
    String[] secondArray = {"ZERO", "ONE", "TWO", "FOUR", "EIGHT", "SIXTEEN"};
    Comparator<String> comparator = String.CASE_INSENSITIVE_ORDER;
    assertEquals(2, Arrays.mismatch(firstArray, 0, 4, secondArray, 1, 3, comparator));
}

5. Conclusion

5.结论

In this article, we computed the first mismatch between two arrays. Java 9 introduced the mismatch() method for this purpose. We saw that this method is convenient in many cases because it offers a large set of overriding.

在本文中,我们计算了两个数组之间的首次不匹配。Java 9 为此引入了 mismatch() 方法。我们看到,该方法在许多情况下都很方便,因为它提供了大量的重载。

As always, the code is available over on GitHub.

与往常一样,代码可在 GitHub 上获取。