In Java, Arrays.compareUnsigned(a, b) works like Arrays.compare: it finds the first index where two arrays differ and orders them by those elements, with a shorter prefix coming first. The difference is that elements are compared as unsigned numbers.
Java's byte, short, int, and long are signed, so the byte 0xFF is -1. Read as unsigned, the same bits mean 255. Binary data such as hashes, network packets, and database keys is usually meant to be ordered that way, and that is where this method helps.
A static method of java.util.Arrays (Java 9+): call it on the class, as in Arrays.compareUnsigned(...); 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, compare the elements in a loop with Byte.toUnsignedInt, Integer.compareUnsigned, or Long.compareUnsigned, all of which exist since Java 8.
Syntax
Pass two arrays of the same integer type; check the sign.
Java
byte[] a = {(byte) 0xFF}; // -1 signed, 255 unsigned
byte[] b = {1};
Arrays.compare(a, b) < 0; // true: -1 < 1
Arrays.compareUnsigned(a, b) > 0; // true: 255 > 1
Only the four integer types have it: byte[], short[], int[], and long[], each with a range form. For non-negative values the result agrees with compare; it differs only when a negative value is involved.
Library declarations
Java
// java.util.Arrays (since Java 9)
public static int compareUnsigned(byte[] a, byte[] b)
public static int compareUnsigned(byte[] a, int aFromIndex, int aToIndex,
byte[] b, int bFromIndex, int bToIndex)
public static int compareUnsigned(int[] a, int[] b)
// also short[] and long[], each with a range form
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.
Return Value
Return Value
Description
int
Negative, zero, or positive, like compare. Test only the sign.