从另一个函数返回`Comparator`

Sha*_*nky 7 java comparator

首先,请告诉我,我受API设计的限制,所以请不要更改API,但是可以添加私有功能.

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
}
Run Code Online (Sandbox Code Playgroud)

当我尝试覆盖方法中的compare函数时出现问题slopeOrder().我试图compare()slopeOrder()函数中调用该方法,但由于我在API中没有任何参数,我不能.

请建议一些Comparator<Point>slopeOrder()方法中返回a的解决方案.

And*_*eas 7

由于该slopeOrder()方法的描述是:

比较他们用一点做出的斜率两个点

这意味着您需要比较通过调用slopeTo(Point that)每个对象返回的值.鉴于该方法的返回值为a 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));
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

在Java 8中,编写lambda表达式要简单得多:

public Comparator<Point> slopeOrder() {
    return (o1, o2) -> Double.compare(slopeTo(o1), slopeTo(o2));
}
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,都会在slopeTo()呼叫this对象上进行slopeOrder()呼叫.


Jor*_*nee 6

您可以Comparator<...>使用lambda表达式实例化a :

public Comparator<Point> slopeOrder() {
    return (a, b) -> {
        // code here
    };
}
Run Code Online (Sandbox Code Playgroud)

在这里,a并且b要比较的点.

或者如果你低于java 8,你必须使用匿名类:

public Comparator<Point> slopeOrder() {
    return new Comparator<Point>() {
        @Override
        public int compare(Point a, Point b) {
            // code here
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

如果Comparator是无状态,您可以创建1个实例并将其保存为static final字段,并始终返回该实例.

当然,您也可以花很长时间来创建一个实现的新类Comparator<Point>,并实例化该类.