代码之家  ›  专栏  ›  技术社区  ›  timurichk

我的类不重写抽象方法compareTo

  •  0
  • timurichk  · 技术社区  · 7 年前

    我的课详细介绍了市中心餐馆的属性,这些属性是x/y位置和排名。问题是,每当我运行程序时,它都会抛出一个错误,即非抽象类“Downtown”不会重写抽象方法“compareTo”。我不能使这个类抽象,因为我需要在这段代码之外初始化对象。我的程序哪里出错了?我的compareTo实现有问题吗?如有任何建议,我们将不胜感激。

    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+' '+"]";
        }
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Sergey Kalinichenko    7 年前

    Java的 Comparable<T> 接口定义 compareTo 方法如下:

    int compareTo(T o);
    

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

    编译器将通过使用 @Override annotation 关于您的方法:

    @Override // Issues an error
    public int compareTo(Downtown p1, Downtown p2)
    
    @Override // Compiles fine
    public int compareTo(Downtown other)
    
        2
  •  1
  •   Dawood ibn Kareem    7 年前

    这个 compareTo 方法应比较 现在的 对象( this )只是 另外不应该这样 用于比较的参数。你可以这样写你的方法。

    public int compareTo(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(getX(),p2.getX());
        if (xResult != 0)
        {
            return xResult;
        }
    
        // Next by y
        int yResult = Integer.compare(getY(),p2.getY());
        if (yResult != 0)
        {
            return yResult;
        }
    
        // Finally by rank
        return Integer.compare(getRank(),p2.getRank());
    }
    

    注意我是如何替换上的所有通话的 p1 调用当前对象。