DEV Community

aurban28
aurban28

Posted on

Arrays.mismatch() and Arrays.compare() in Java

When working with arrays in Java, the Arrays class offers several methods to manipulate and compare arrays. Two such methods are mismatch and compare, both of which deal with array comparison but serve different purposes. Here's a breakdown of how they differ:

1. Arrays.compare(T[] a, T[] b)
The compare method compares two arrays lexicographically. This means it checks the elements of both arrays sequentially, starting from the first element, then the second, and so on, until it finds a difference or reaches the end of both arrays.

Returns:

  • A negative integer if the first array is lexicographically less than the second array.
  • 0 if the arrays are identical.
  • A positive integer if the first array is lexicographically greater than the second. This is similar to how strings are compared lexicographically.

Example:

int[] a = {1, 2, 3};
int[] b = {1, 2, 4};

int result = Arrays.compare(a, b); // Returns a negative number because 3 < 4
Enter fullscreen mode Exit fullscreen mode

2. Arrays.mismatch(T[] a, T[] b)
The mismatch method finds the index of the first differing element between two arrays. It compares elements one by one until it encounters a difference or finishes checking all elements.

Returns:

  • The index of the first mismatch between the two arrays.
  • -1 if both arrays are identical (i.e., they have the same length and elements).

Example:

int[] a = {1, 2, 3};
int[] b = {1, 2, 4};

int index = Arrays.mismatch(a, b); // Returns 2, because a[2] != b[2]
Enter fullscreen mode Exit fullscreen mode

Key Differences:
Purpose:

  • compare is used to determine the lexicographical order of two arrays.
  • mismatch is used to find the exact point where two arrays differ.

Result:

  • compare returns an integer representing the order relation between the arrays.
  • mismatch returns the index of the first differing element, or -1 if the arrays are equal.

In summary, use compare when you need to sort or lexicographically compare arrays, and use mismatch when you need to pinpoint where the arrays diverge.

Top comments (0)