In Java, Arrays.compare(a, b) compares two arrays lexicographically, the way a dictionary orders words: the first index where the elements differ decides. If one array is a prefix of the other, the shorter one comes first.
The result is negative if a comes first, zero if the arrays are equal, and positive if a comes after b. Only the sign is meaningful, so test < 0 or > 0 rather than expecting -1 or 1.
A static method of java.util.Arrays (Java 9+): call it on the class, as in Arrays.compare(...); there is no Arrays object to create.
Java 9+ only.
Added in Java 9: the examples need JDK 9 or newer, and on Java 8 the call fails with "cannot find symbol". On Java 8, loop to the first differing index and compare those elements with Integer.compare; if none differ, compare the lengths.
Syntax
Pass two arrays of the same type; check the sign of the result.
Java
int[] a = {1, 2, 3};
int[] b = {1, 3};
Arrays.compare(a, b) < 0; // true: 2 < 3 at index 1
Arrays.compare(b, a) > 0; // true
Arrays.compare(a, new int[] {1, 2, 3}); // 0
Call
What it does
Arrays.compare(a, b)
Order of two primitive or Comparable arrays.
Arrays.compare(x, y, comparator)
Object elements compared with a comparator.
Arrays.compare(a, aFrom, aTo, b, bFrom, bTo)
Compares a range of each array.
Arrays.sort(rows, (x, y) -> Arrays.compare(x, y))
Sort an int[][] row by row.
Overloads cover every primitive type (for boolean[], false < true), Comparable object arrays, and object arrays with a Comparator, each with a range form.
Library declarations
Java
// java.util.Arrays (since Java 9)
public static int compare(int[] a, int[] b)
public static <T extends Comparable<? super T>> int compare(T[] a, T[] b)
public static <T> int compare(T[] a, T[] b, Comparator<? super T> cmp)
// range form: compare(a, aFromIndex, aToIndex, b, bFromIndex, bToIndex)
// also boolean[], byte[], short[], char[], long[], float[], double[]
Parameters
Parameter
Description
a, b
The arrays to compare. In the two-array forms, either may be null.
range indexes (optional)
From (inclusive) and to (exclusive) indexes for each array.
cmp (optional)
Comparator for the elements of object arrays.
Return Value
Return Value
Description
int < 0
a comes first: smaller at the first difference, or a proper prefix of b.