[英]Sorting issue with 2D array in JAVA
With my following code I try to sort a two dimensional array 通过下面的代码,我尝试对二维数组进行排序
int[][] d2 = {
{4,5,1},
{4,1,1},
{1,7,1},
{3,3,2},
{1}
};
java.util.Arrays.sort(d2, new java.util.Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
});
I display the array after sorting 我在排序后显示数组
for (int r=0; r<d2.length; r++) {
for (int c=0; c<d2[r].length; c++) {
System.out.print(" " + d2[r][c]);
}
System.out.println("");
}
The Result I get is like this 我得到的结果是这样的
1 7 1
1
3 3 2
4 5 1
4 1 1
I want the result two come like this 我希望结果两个像这样
1
1 7 1
3 3 2
4 5 1
4 1 1
What is required to be done to get the array sorted like the above? 要像上面那样对数组进行排序需要做什么?
I tried replacing the {1}
with {1,0,0}
but it still gives the same result even for {1,0,1}
. 我尝试用{1,0,0}
替换{1}
,但是即使对于{1,0,1}
它仍然给出相同的结果。
Compare the length of passed array in the compare
method.. If length of a[]
is less than b[]
, return -1: - 在compare
方法中compare
传递的数组的长度。如果a[]
长度小于b[]
,则返回-1:-
java.util.Arrays.sort(d2, new java.util.Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if (a.length != b.length) {
return a.length < b.length ? -1 : 1;
}
return a[0] - b[0];
}
});
If you want to sort, by checking each element, which I think you should do this way.. Change your compare
method to: - 如果您想通过检查每个元素来进行排序,我认为您应该这样做。.将您的compare
方法更改为:-
public int compare(int[] a, int[] b) {
if (a.length == b.length) {
for (int i = 0; i < a.length; i++) {
if (a[i] == b[i]) {
} else {
return a[i] - b[i];
}
}
return 0;
} else {
return a.length < b.length ? -1 : 1;
}
}
In your Comperator
you only use the first field to compare 2 arrays. 在您的Comperator
您仅使用第一个字段比较2个数组。 You have to include all the fields to compare them or at least you have to check the length of the arrays to get your desired result. 您必须包括所有字段以进行比较,或者至少必须检查数组的长度才能获得所需的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.