java.nio.IntBuffer#wrap(int[]) 提供了一种出色的内置方法来比较int[] 的两个实例,因为IntBuffer 是int[] 实例的轻量级包装器,和 实现了Comparable。将它与其他内置 Comparator 功能结合使用与我在此处看到的其他答案中的示例相比有几个优势:
- 比较所有子数组元素
- 支持可变子数组长度
- 支持
null数组元素
此示例按降序对数组进行排序,将null 数组元素放在最后:
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));
输出:
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]