Comparing arrays – Java 9 Arrays utilities

/, Java 9/Comparing arrays – Java 9 Arrays utilities

Comparing arrays :

For comparing arrays and slices of arrays more static utility methods are added to java.util.Arrays. Below are the list of overloaded static methods added in JDK 9 to the Arrays utility class.

  1. equals – returns true if two arrays are equal to each other.
  2. compare – compares two arrays lexicographically (similar to dictionary order).
  3. mismatch – finds and returns the index of the first mismatch between two arrays.

equals method :

equals() returns true if two arrays are equal to each other. There are two different version of different overloads for boolean, byte, char, double, float, int, long, short and Object arrays. Version one for equality check for two arrays and version two for equality check for slices of two arrays. Two arrays are considered equal if both are null.

Example:

Output:

compare and compareUnsigned methods :

The group of methods compare() and compareUnsigned() compares two arrays lexicographically. There are two different version of different overloads for boolean, byte, char, double, float, int, long, short and Object arrays. Version one for equality check for two arrays and version two for equality check for slices of two arrays. The compareunsigned method treats the integer values as unsigned and this overloaded method applicable only for data types which can be signed.

  1. A null array is lexicographically less than a non-null array.
  2. Two arrays are considered equal if both are null.
  3. If first array and second array are equal then compare() returns zero;
  4. If the first array (or slice) is lexicographically less than the second array (or slice) returns -ve (negative value).
  5. If the first array (or slice) is lexicographically greater than the second array (or slice) returns +ve (positive value).

Example:

Output:

mismatch method :

The group of methods mismatch() finds and returns the index of the first mismatch between two arrays. There are different overloads for boolean,
byte, char, double, float, int, long, short and Object arrays. We can also specify the start and end index in both arrays for checking the mismatch.

  1. mismatch() returns -1 if there is no mismatch.
  2. If either array is null, it throws a NullPointerException.

Example:

Output: