java.nio.IntBuffer#wrap(int[])
provides an excellent built-in way to compare two instances of int[]
, since IntBuffer
is both a lightweight wrapper for int[]
instances, and implements Comparable
. Using it combined with other built-in Comparator
features has several advantages over the examples in other answers I see here:
- Compares all sub-array elements
- Supports variable sub-array lengths
- Supports
null
array elements
This example sorts the arrays in descending order, putting null
array elements last:
int[][] twoDim = {{1, 2}, {3, 7}, {8, 9}, {4, 2}, null, {5, 3}, {4}};
System.out.println("Unsorted: " + Arrays.deepToString(twoDim));
Comparator<int[]> c = Comparator.nullsFirst(Comparator.comparing(IntBuffer::wrap));
Arrays.sort(twoDim, c.reversed());
System.out.println("Sorted: " + Arrays.deepToString(twoDim));
Output:
Unsorted: [[1, 2], [3, 7], [8, 9], [4, 2], null, [5, 3], [4]]
Sorted: [[8, 9], [5, 3], [4, 2], [4], [3, 7], [1, 2], null]