当前位置: 首页 > 知识库问答 >
问题:

我的类不重写抽象方法compareTo

岑明辉
2023-03-14
public class Downtown implements Comparable<Downtown> {//Throws error on this line
    private int x;
    private int y;
    private int rank;

    public Downtown(int x, int y, int rank) {
        this.x = x;
        this.y = y;
        this.rank = rank;
    }
    //Appropriate setters and getters for x , y and rank
    public int getX() {
         return x;
    }
    public void setX(int x) {
    this.x = x;
    }
    public int getY() {
    return y;
    }
    public void setY(int y) {
    this.y = y;
    }
    public int getRank() {
    return rank;
    }
    public void setRank(int rank) {
    this.rank = rank;
    }   

    public int compareTo(Downtown p1, Downtown p2)//Actual comparison
    {
        // This is so that the sort goes x first, y second and rank last

        // First by x- stop if this gives a result.
        int xResult = Integer.compare(p1.getX(),p1.getX());
        if (xResult != 0)
        {
            return xResult;
        }

        // Next by y
        int yResult = Integer.compare(p1.getY(),p2.getY());
        if (yResult != 0)
        {
            return yResult;
        }

        // Finally by rank
        return Integer.compare(p1.getRank(),p2.getRank());
    }

    @Override
    public String toString() {
        return "["+x+' '+y+' '+rank+' '+"]";
    }

共有1个答案

李昌勋
2023-03-14

Java的可比 接口定义compareto方法如下:

int compareTo(T o);

这意味着该方法必须接受一个参数;另一个参数是对象本身,即this。您需要实现这个单参数方法来代替您的双参数方法来解决这个问题。

编译器将通过在方法上使用@override注释来帮助您解决此类问题:

@Override // Issues an error
public int compareTo(Downtown p1, Downtown p2)

@Override // Compiles fine
public int compareTo(Downtown other)
 类似资料: