gpt4 book ai didi

java - 对 2 个 arraylist 进行排序,每个 arraylist 代表 x 和 y 坐标

转载 作者:行者123 更新时间:2023-12-02 12:08:58 24 4
gpt4 key购买 nike

我有2个数组列表

xVal:[9 8 6 5 4 3 2 -10]
y值:[3 6 5 7 9 1 8 10]

我想按升序对 xVal 进行排序,并且在 xVal 排序时也有相应的 yVal 进行移动。

所以结果是

xVal:[-10 2 3 4 5 6 8 9 ]
y值:[10 8 1 9 7 5 6 3]

感谢您抽出时间来解释

最佳答案

我想建议您在这里使用不同的数据结构。您可以为 x/y 坐标创建一个自己的数据类型 (POJO),然后可以以“正常”Java 方式对列表进行排序。

这是您可以使用的 POJO:

public class Coordinate {
public int x;
public int y;

public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}

@Override
public String toString() {
return "[" + x + ", " + y + "] ";
}
}

主程序初始化列表,根据 X 坐标对坐标进行排序,然后显示结果:

public class SortDemo {
public static void main(String[] args) {
// init the list
List<Coordinate> coordinates = new ArrayList<>();
coordinates.add(new Coordinate(9, 3));
coordinates.add(new Coordinate(8, 6));
coordinates.add(new Coordinate(6, 5));
coordinates.add(new Coordinate(5, 7));
coordinates.add(new Coordinate(4, 9));
coordinates.add(new Coordinate(3, 1));
coordinates.add(new Coordinate(2, 8));
coordinates.add(new Coordinate(-10, 10));

// sort
Collections.sort(coordinates, (coordinate1, coordinate2) -> coordinate1.x - coordinate2.x);

// display the content of the sorted list
System.out.println(coordinates);
}
}

结果:

[-10, 10] , [2, 8] , [3, 1] , [4, 9] , [5, 7] , [6, 5] , [8, 6] , [9, 3]

编辑

toString():

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

例如:

Coordinate coordinate = new Coordinate(-10, 10);
System.out.println(coordinate);

或者

Coordinate coordinate = new Coordinate(-10, 10);
System.out.println(coordinate.toString());

您可以在 IDE 的 DEBUG 模式下检查它。

排序

前面提到的集合排序的缩写形式与此等效:

class MySort implements Comparator<Student> {
public int compare(Coordinate coordinate1, Coordinate coordinate2) {
return coordinate1.x - coordinate2.x;
}
}

// how to use
Collections.sort(coordinates, new MySort());

API doc of compare()

关于java - 对 2 个 arraylist 进行排序,每个 arraylist 代表 x 和 y 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46694289/

24 4 0