根据坐标值排序

时间:2018-05-22 12:38:33

标签: java

我一直在尝试根据X的值对ArrayList个坐标进行排序。到目前为止,我已经能够对升序或降序进行排序,但这对于Exception in thread "AWT-EventQueue-0 java.util.ConcurrentModificationException内的所有内容都是如此。 。如果我尝试将排序放在2中,如果检查值是偶数还是奇数,我总是得到package TSP.TSP_Algo; import TSP.Coordinate; import TSP_Algorithm; import java.awt.*; import java.lang.reflect.Array; import java.util.*; import java.util.List; public class Convex extends TSP_Algorithm { private ArrayList<Coordinate> coords; private ArrayList<Coordinate> sortedCoords = new ArrayList<>(); public Convex(ArrayList<Coordinate> coords) { this.coords = coords; ArrayList<Coordinate> coordinaten = this.coords; } public ArrayList<Coordinate> getSortedCoordinates() { ArrayList<Point> Points = coordToPoint(coords); for (Point points : Points) { Coordinate Even = new Coordinate(0, 0); Coordinate Odd = new Coordinate(0, 0); if (points.x % 2 == 0) { Points.sort(new PointYAscending()); Points.sort(new PointXAscending()); Even.x = points.x; Even.y = points.y; sortedCoords.add(Even); } if (points.x % 2 != 0) { Points.sort(new PointXDescending()); Points.sort(new PointYDescending()); Odd.x = points.x; Odd.y = points.y; sortedCoords.add(Odd); } } return sortedCoords; } private ArrayList<Point> coordToPoint(ArrayList<Coordinate> coords) { ArrayList<Point> points = new ArrayList<>(); for (Coordinate coord : coords) { points.add(new Point(coord.x, coord.y)); } return points; } public class PointXAscending implements Comparator<Point> { public int compare(Point a, Point b) { { return Integer.compare(a.x, b.x); } } } public class PointXDescending implements Comparator<Point> { public int compare(Point a, Point b) { { return Integer.compare(b.x, a.x); } } } public class PointYDescending implements Comparator<Point> { public int compare(Point a, Point b) { { return Integer.compare(b.y, a.y); } } } public class PointYAscending implements Comparator<Point> { public int compare(Point a, Point b) { { return Integer.compare(a.y, b.y); } } } } 错误。我如何从这一点走得更远?这是我到目前为止的代码:

#strange-behaviour {
  direction: rtl;
}

2 个答案:

答案 0 :(得分:0)

您的问题是您的代码格式为:

for (Point points : Points) {
    //...
    Points.sort(new PointYAscending());
    //...
}

首先,逻辑上这没有意义。 “对于每一点,对所有点进行排序。”为什么?您只需拨打sort一次。

其次,这不合法。循环时,您无法修改列表。 sort正在修改列表的结构,使其无法正确迭代它,从而引发异常。

您的代码应该是:

ArrayList<Point> points = coordToPoint(coords);
points.sort(new PointXAscending().thenComparing(new PointYAscending()));
return points;

答案 1 :(得分:0)

您正在尝试修改(排序)列表,同时迭代。这是不允许的。您需要从代码中删除以下行:

        Points.sort(new PointYAscending());
        Points.sort(new PointXAscending());

重复两次。