Collections.sort 不适用于列表<Point2D.Double>

Collections.sort doesn't work on List<Point2D.Double>

我在我的绘图器中使用 List<Point2D.Double> serie 来存储点坐标。当我要排序的时候,我决定使用Collections.sort(serie)但是它显示有一个像

这样的错误

There can't be double type

那么如何按 x 坐标对 List<Point2D.Double> 进行排序?

Point2D 没有实现 Comparable 接口。您将需要创建一个自定义 Comparator 来执行您想要的操作,并将其与您的列表一起传递给 sort 方法,例如...

Collections.sort(serie, new Comparator<Point2D.Double>() {
    public int compare(Point2D.Double p1, Point2D.Double p2) {
        return (int)(p1.getX() - p2.getX());
    }
});

Collections.sort(List<T>)documentation 可以看到

All elements in the list must implement the Comparable interface

强制执行
public static <T extends Comparable<? super T>> void sort(List<T> list)

因此应声明列表以存储 extends/implements ComparablePoint2D.Double 未实现 Comparable 类型的元素,因此它不是有效类型。

对于这种情况 Java 添加

public static <T> void sort(List<T> list, Comparator<? super T> c)

允许您创建自己的 Comparator 的方法,以便您可以比较未实现 Comparable 的元素,或者以不同于预定义的方式比较它们。

所以你的代码可以看起来像

Collections.sort(serie, new Comparator<Point2D.Double>() {
    public int compare(Point2D.Double p1, Point2D.Double p2) {
        return Double.compare(p1.getX(), p2.getX());
    }
});

或者你可以写成Java 8 like

Collections.sort(serie, Comparator.comparingDouble(Point2D.Double::getX));

甚至

serie.sort(Comparator.comparingDouble(Point2D.Double::getX));