英文:
sorting 2d array using build in sort function
问题
使用 Arrays.sort() 函数对二维数组(int[][] array)进行排序。因为我想要根据第一个元素进行排序。例如,{{2,3},{1,4}} 根据第一个元素排序后数组将变为 {{1,4},{2,3}}。因此,我重写了比较函数。
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2){
if(o1[0] < o2[0]){
return -1;
} else if (o1[0] > o2[0]) {
return 1;
} else {
return 0;
}
}
})
我知道这个排序是有效的,但我不明白这个比较函数是如何工作的。
我原本认为
new Comparator<int[]>
应该是
new Comparator<int[][]>
因为这是一个二维数组。在比较函数内部,应该比较
o1[0][0] 和 o2[0][0]
有人可以帮助我理解吗?
另外,这里使用了 Arrays.sort,我可以使用 Collections.sort 吗?它们之间有什么区别?
谢谢
<details>
<summary>英文:</summary>
I was using Arrays.sort() function to sort 2d array (int[][] array). Since I want to sort it base on the first element. For example, {{2,3},{1,4}} base on 1st element the array will be {{1,4},{2,3}}. So I override the compare function.
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2){
if(o1[0] < o2[0]){
return -1;
} else if (o1[0] > o2[0]) {
return 1;
} else {
return 0;
}
}
})
I know this sort work. But I don't understand how this compare work.
I was thinking the
new Comparator<int[]>
should be
new Comparator<int[][]>
since this is 2d array. and inside of compare function should be compare
o1[0][0] and o2[0][0]
Can anyone help me understand it?
Also this is using Arrays.sort, can I use Collections.sort? what is different between it?
Thanks
</details>
# 答案1
**得分**: 0
记住,在Java中实际上不存在所谓的“2D数组”,所以你实际上正在处理的是“一个`int[]`数组”(没有固有的限制,每个`int[]`的长度可以不同)。
因此:在排序时,你正在将“`int[]`数组”中的单个元素相互进行比较,因为每个元素都是一个`int[]`,所以你的比较器也是针对`int[]`的。
<details>
<summary>英文:</summary>
Remember that a "2D array" doesn't actually exist in Java, so what you're really dealing with is "an array of `int[]`" (there's nothing inherently preventing each of those `int[]` from being a different length).
So: when you sort, you're comparing individual elements of that "array of `int[]`" with each other, and because each element is an `int[]`, your Comparator is for `int[]`, too.
</details>
# 答案2
**得分**: 0
你正在将数组传递给排序方法,并为其提供了一个比较器。Arrays.sort 将使用迭代器传递到比较方法中。因此,比较方法正在检查 arr[0] 处的元素。arr[0].compare(arr[1]) 对这两个元素进行排序,然后进入下一个迭代器。在使用二维数组时,相同的概念适用。你只需传递两个数组,并告诉比较方法谁应该放在哪个位置。
<details>
<summary>英文:</summary>
You are passing the array in the sort method and giving it a comparator. Arrays.sort will use iterator to pass into compare method. So compare method is checking element at arr[0].compare(arr[1]) sorts these 2 and goes to next iterator. same concept applies using 2d array. You are just passing 2 arrays and telling compare who should be placed where.
</details>
专注分享java语言的经验与见解,让所有开发者获益!
评论