[英]Comparator for Java Point2D does not work
I have an array of 2D points in Java and want to sort it.我在 Java 中有一个二维点数组,想要对其进行排序。 I have used comparators from different websites, like for example from Collections.sort doesn't work on List<Point2D.Double> but none of them work for me.我使用了来自不同网站的比较器,例如来自Collections.sort 的比较器在 List<Point2D.Double> 上不起作用,但它们都不适合我。
If I for example use the following code:例如,如果我使用以下代码:
Point2D[] points = new Point2D[numPoints];
// add some points
Collections.sort(points, new Comparator<Point2D.Double>() {
public int compare(Point2D.Double p1, Point2D.Double p2) {
return (int)(p1.getX() - p2.getX());
}
});
I always get the following error message:我总是收到以下错误消息:
error: no suitable method found for sort(Point2D[],<anonymous Comparator<Double>>)
Collections.sort(points, new Comparator<Point2D.Double>() {
^
method Collections.<T#1>sort(List<T#1>) is not applicable
(cannot infer type-variable(s) T#1
(actual and formal argument lists differ in length))
method Collections.<T#2>sort(List<T#2>,Comparator<? super T#2>) is not applicable
(cannot infer type-variable(s) T#2
(argument mismatch; Point2D[] cannot be converted to List<T#2>))
where T#1,T#2 are type-variables:
T#1 extends Comparable<? super T#1> declared in method <T#1>sort(List<T#1>)
T#2 extends Object declared in method <T#2>sort(List<T#2>,Comparator<? super T#2>)
1 error
Is there any obvious reason for that?有什么明显的原因吗?
You have an array ...[]
hence you need Arrays.sort
, not Collections.sort
which is for any Collection like List.你有一个数组...[]
因此你需要Arrays.sort
,而不是Collections.sort
,它适用于像列表这样的任何集合。
Arrays.sort(points,
Comparator.comparingDouble(Point2D::getX)
.thenComparingDouble(Point2D::getY));
Furthermore Comparator
has nice methods for (several) comparing fields.此外, Comparator
有用于(多个)比较字段的好方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.