[英]Sorting a 2d array in Java
Im having a little of a hard time figuring out the specifics of a line of code that sorts a 2d array of integers.我很难弄清楚对二维整数数组进行排序的代码行的细节。
The array that is being sorted is an array that has arrays inside that only have two numbers, I am trying to figure out if (a, b)
refers to two separate 2d arrays and if (a[0], b[0])
refers to the numbers within the 2d arrays?正在排序的数组是一个包含 arrays 的数组,里面只有两个数字,我试图弄清楚
(a, b)
是否指两个单独的 2d arrays 和 if (a[0], b[0])
指的是 2d arrays 内的数字?
Arrays.sort(sortedIntervals, (a, b) -> Integer.compare(a[0], b[0]));
You can use key extractor and comparator chaining :您可以使用密钥提取器和比较器链接:
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]));
Arrays.sort(sortedIntervals, (a,b) -> Integer.compare(a[0], b[0]));
As you can see here there is only one method compare: compare(int,int)
.正如您在此处看到的,只有一种方法 compare:
compare(int,int)
。 So a[0]
must be a int (or a java.lang.Integer, respecievly).所以
a[0]
必须是一个 int (或 java.lang.Integer,分别)。
Since there is only one method accepting a lambda as second parameter it must be this method .由于只有一种方法接受 lambda 作为第二个参数,所以它必须是这个方法。 And it's javadoc sais
a
and b
are direct elements of the array sortedIntervals
and a
and b
must be an array of ints.它的 javadoc sais
a
和b
是数组sortedIntervals
的直接元素, a
和b
必须是整数数组。
So there is no other option than sortedIntervals
is a 2dim array of integers.所以除了
sortedIntervals
是一个 2dim 整数数组之外没有其他选择。 Since we can access a[0] and b[0] we can expect that all direct elements of sortedIntervals
have in their first position can be cast to int
.由于我们可以访问 a[0] 和 b[0] 我们可以预期
sortedIntervals
的所有直接元素在它们的第一个 position 中可以转换为int
。
Also we can predict that我们也可以预测
int[][] sortedIntervals ={{},{}};
int[][] sortedIntervals ={{6},{}};
int[][] sortedIntervals ={{},{6}};
will always throw a ArrayIndexOutOfBoundsException
inside the lambda because the index 0
does not exists in at least one of the elements.将始终在 lambda 内抛出
ArrayIndexOutOfBoundsException
异常,因为索引0
在至少一个元素中不存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.