我必须实现一个具有“比较器”的API。但我不知道它是什么以及如何制作它。请帮助。这是我的API:
public class Point implements Comparable<Point> {
public final Comparator<Point> SLOPE_ORDER; // compare points by slope to this point
public Point(int x, int y) // construct the point (x, y)
public void draw() // draw this point
public void drawTo(Point that) // draw the line segment from this point to that point
public String toString() // string representation
public int compareTo(Point that) // is this point lexicographically smaller than that point?
public double slopeTo(Point that) // the slope between this point and that point
}
“公共最终比较者SLOPE_ORDER”是什么意思?以及如何制作?
这是我的代码:
/*************************************************************************
* Name:
* Email:
*
* Compilation: javac Point.java
* Execution:
* Dependencies: StdDraw.java
*
* Description: An immutable data type for points in the plane.
*
*************************************************************************/
import java.util.Comparator;
public class Point implements Comparable<Point> {
// compare points by slope
public final Comparator<Point> SLOPE_ORDER; // YOUR DEFINITION HERE
private final int x; // x coordinate
private final int y; // y coordinate
// create the point (x, y)
public Point(int x, int y) {
/* DO NOT MODIFY */
this.x = x;
this.y = y;
}
// plot this point to standard drawing
public void draw() {
/* DO NOT MODIFY */
StdDraw.point(x, y);
}
// draw line between this point and that point to standard drawing
public void drawTo(Point that) {
/* DO NOT MODIFY */
StdDraw.line(this.x, this.y, that.x, that.y);
}
// slope between this point and that point
public double slopeTo(Point that) {
/* YOUR CODE HERE */
double slope = (that.y*1.0-this.y)/(that.x*1.0-this.x);
return slipe;
}
// is this point lexicographically smaller than that one?
// comparing y-coordinates and breaking ties by x-coordinates
public int compareTo(Point that) {
/* YOUR CODE HERE */
if(this.y<that.y) return 1;
else if(this.y==that.y) {
if(this.x<that.x) return 1;
else return 0;
}
else return 0;
}
// return string representation of this point
public String toString() {
/* DO NOT MODIFY */
return "(" + x + ", " + y + ")";
}
// unit test
public static void main(String[] args) {
/* YOUR CODE HERE */
}
}
答案 0 :(得分:1)
像这样的东西
public final Comparator<Point> SLOPE_ORDER = new Comparator<Point>()
{
@Override
public int compare(Point p0, Point p1)
{
double s0 = slopeTo(p0);
double s1 = slopeTo(p1);
return Double.compare(s0, s1);
}
};