Den*_*nis -1 java sorting collections swing arraylist
我List<Point2D.Double> serie在绘图仪中用于存储点坐标。当我想排序时,我决定使用,Collections.sort(serie)但它表明存在类似的错误
不能有双重类型
那么如何List<Point2D.Double>按x坐标排序?
从您的文档中Collections.sort(List<T>)可以看到
列表中的所有元素必须实现Comparable接口
这是由
public static <T extends Comparable<? super T>> void sort(List<T> list)
Run Code Online (Sandbox Code Playgroud)
因此,名单应该宣布它扩展/实现类型的商店元素Comparable,但Point2D.Double并没有实现Comparable,所以它不是有效的类型。
对于这种情况,Java添加了
public static <T> void sort(List<T> list, Comparator<? super T> c)
Run Code Online (Sandbox Code Playgroud)
允许您创建自己的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());
}
});
Run Code Online (Sandbox Code Playgroud)
或者你可以用Java 8编写它
Collections.sort(serie, Comparator.comparingDouble(Point2D.Double::getX));
Run Code Online (Sandbox Code Playgroud)
甚至
serie.sort(Comparator.comparingDouble(Point2D.Double::getX));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1371 次 |
| 最近记录: |