我有一个对象数组,假设每个对象都是 Grid 类型。
每个 Grid 对象都有 x 和 y 坐标,
Grid temp = new Grid(3, 5);
// temp.x returns x, temp.y returns y.
现在我有几个网格数组
Grid[] theArray1 = new Grid[5];
Grid[] theArray2 = new Grid[5];
Grid[] theArray3 = new Grid[5];
我用 Grid 对象填充数组并使用 Arrays.sort 对它们进行排序。
我现在加入排序的数组以形成长度为 5+5+5=15 的 theArray。
我现在想按“子数组”的第一个元素(theArray 中的元素 0、5 和 10)对 theArray 进行排序
我怎样才能做到这一点?另外,如果有更简单的方法来实现相同的结果,那就太好了。但我必须从 3 个数组开始,因为它们是通过 for 循环的迭代获得的。
编辑:
示例:假设我按 X 坐标排序,较小的优先。 为简单起见,我将每个 Grid[] 的长度设为 3 而不是 5。
Grid[] theArray1 = new Grid[]{new Grid(2, 1), new Grid(4, 1), new Grid(0, 1)};
Grid[] theArray2 = new Grid[]{new Grid(4, 2), new Grid(3, 1), new Grid(7, 1)};
Grid[] theArray3 = new Grid[]{new Grid(1, 7), new Grid(5, 3), new Grid(10, 1)};
我最终想要的是一个数组/数组列表,打印时打印如下:
for (int i = 0; i <= theArray.length-2; i++) {
StdOut.println(theArray[i] + ", " + theArray[i+1] + ", " + theArray[i+2] + "\n");
}
// Output:
(0, 1), (2, 1), (4, 1) //this is theArray1
(1, 7), (5, 3), (10, 1) //this is theArray3
(3, 1), (4, 2), (7, 1) //this is theArray2
首先,我对每个 theArray(1、2 和 3) 进行排序,使具有最低 x 坐标的元素排在第一位,然后是第二小的,然后是最大的。
然后我根据每个数组的第一个元素的大小排列这些数组。 theArray3 在 theArray2 之前,因为第一个元素的 x 坐标是 1 但在 theArray2 中是 3
最佳答案
假设Grid
工具 Comparable<Grid>
,对每个数组进行排序并添加到二维数组。然后使用 Arrays.sort(Grid[][], GridArrayComparator)
对该网格数组进行排序, 其中GridArrayComparator
看起来像:
class GridArrayComparator implements Comparator<Grid[]> {
public int compare(Grid[] grids1, Grid[] grids2) {
if (grids1.length > 0 && grids1.length > 0) {
return grids1[0].compareTo(grids2[0]);
} else if (grids1.length > 0) {
return 1;
} else if (grids2.length > 0) {
return -1;
} else {
return 0;
}
}
}
然后将二维数组复制到一维数组。
关于java - 根据第一个元素对子数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18991861/