我一直试图根据X的值对坐标的ArrayList进行排序,到目前为止,我已经能够按升序或降序对坐标进行排序,但这适用于ArrayList中的所有内容。如果我试图将排序放在2中,检查值是偶数还是奇数,我总是会得到一个Exception in thread "AWT-EventQueue-0 java.util.ConcurrentModificationException错误。从现在开始,我该怎么做呢?这是我到目前为止掌握的代码:
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);
}
}
}
}发布于 2018-05-22 12:42:47
您的问题是,您的代码具有以下形式:
for (Point points : Points) {
//...
Points.sort(new PointYAscending());
//...
}首先,从逻辑上讲,这是没有道理的。“对每一点,对所有要点进行排序。”为什么?您只需要调用sort一次。
第二,这是不合法的。当您在列表上循环时,不能修改它。sort正在修改列表的结构,使得不可能正确地迭代它,从而引发异常。
您的代码可能应该是:
ArrayList<Point> points = coordToPoint(coords);
points.sort(new PointXAscending().thenComparing(new PointYAscending()));
return points;发布于 2018-05-22 12:46:40
您正在尝试在迭代列表时修改(排序)列表。这是不允许的。您需要从代码中删除以下行:
Points.sort(new PointYAscending());
Points.sort(new PointXAscending());重复两次。
https://stackoverflow.com/questions/50467946
复制相似问题