首先,请让我清楚,我受API设计的限制,所以请不要更改API,但是可以添加私有(private)函数。
public class Point implements Comparable<Point> {
public Point(int x, int y) // constructs the point (x, y)
public void draw() // draws this point
public void drawTo(Point that) // draws the line segment from this point to that point
public String toString() // string representation
public int compareTo(Point that) // compare two points by y-coordinates, breaking ties by x-coordinates
public double slopeTo(Point that) // the slope between this point and that point
public Comparator<Point> slopeOrder() // compare two points by slopes they make with this point
}
当我尝试覆盖 slopeOrder()
中的比较函数时出现问题方法。我试着调用 compare()
slopeOrder()
中的方法函数,但由于我在 API 中没有任何参数,所以我不能。
请提出一些解决方案以返回 Comparator<Point>
来自 slopeOrder()
方法。
最佳答案
因为 slopeOrder()
方法的描述是:
compare two points by slopes they make with this point
这意味着您需要比较通过对每个对象调用 slopeTo(Point that)
返回的值。鉴于该方法的返回值为 double
,这意味着您需要调用 Double.compare()
.
在 Java 8 之前的版本中,您将使用匿名类来实现它:
public Comparator<Point> slopeOrder() {
return new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
return Double.compare(slopeTo(o1), slopeTo(o2));
}
};
}
在 Java 8 中,将其编写为 lambda 表达式要简单得多:
public Comparator<Point> slopeOrder() {
return (o1, o2) -> Double.compare(slopeTo(o1), slopeTo(o2));
}
或者使用方法引用:
public Comparator<Point> slopeOrder() {
return Comparator.comparingDouble(this::slopeTo);
}
在所有情况下,slopeTo()
调用都是在 slopeOrder()
调用的 this
对象上进行的。
关于java - 从另一个函数返回 `Comparator`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39677697/