繁体   English   中英

在 Java 中对二维数组进行排序

[英]Sorting a 2d array in Java

我很难弄清楚对二维整数数组进行排序的代码行的细节。

正在排序的数组是一个包含 arrays 的数组,里面只有两个数字,我试图弄清楚(a, b)是否指两个单独的 2d arrays 和 if (a[0], b[0])指的是 2d arrays 内的数字?

Arrays.sort(sortedIntervals, (a, b) -> Integer.compare(a[0], b[0]));

您可以使用密钥提取器比较器链接

int[][] arr2d = {{1, 3, 6}, {1, 2, 3}, {0, 2, 3}};

// sorting the rows of a 2d array first by
// the first column, then by the second column
Arrays.sort(arr2d, Comparator
        .<int[]>comparingInt(row -> row[0])
        .thenComparingInt(row -> row[1]));

System.out.println(Arrays.deepToString(arr2d));
// [[0, 2, 3], [1, 2, 3], [1, 3, 6]]

Arrays.sort(sortedIntervals, (a,b) -> Integer.compare(a[0], b[0]));

正如您在此处看到的,只有一种方法 compare: compare(int,int) 所以a[0]必须是一个 int (或 java.lang.Integer,分别)。

由于只有一种方法接受 lambda 作为第二个参数,所以它必须是这个方法 它的 javadoc sais ab是数组sortedIntervals的直接元素, ab必须是整数数组。

所以除了sortedIntervals是一个 2dim 整数数组之外没有其他选择。 由于我们可以访问 a[0] 和 b[0] 我们可以预期sortedIntervals的所有直接元素在它们的第一个 position 中可以转换为int

我们也可以预测

int[][] sortedIntervals ={{},{}}; 
int[][] sortedIntervals ={{6},{}}; 
int[][] sortedIntervals ={{},{6}}; 

将始终在 lambda 内抛出ArrayIndexOutOfBoundsException异常,因为索引0在至少一个元素中不存在。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM