Collections.sort不能在List <point2d.double> </point2d.double>上工作

时间:2015-03-13 10:50:50

标签: java swing sorting arraylist collections

我在我的画家中使用List<Point2D.Double> serie来存储点坐标。当我想要排序时,我决定使用Collections.sort(serie),但它表明存在像

这样的错误
  

不能是双重型

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

2 个答案:

答案 0 :(得分:5)

来自Collections.sort(List<T>)的{​​{3}},您可以看到

  

列表中的所有元素都必须实现Comparable接口

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

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

对于这种情况,Java添加

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

允许您创建自己的比较器的方法,以便您可以比较不能实现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中编写

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

甚至

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

答案 1 :(得分:2)

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());
    }
});
相关问题