Java:实现 Comparable 接口时出现问题

Java: Problems implementing the Comparable interface

我正在学习 Java 并正在做一些简单的编程问题。其中之一是在 Octagon class 中实现 Comparable 接口,以允许根据边长对八边形进行排名。这是我的代码片段:

class Octagon implements Comparable
  {
    private double side;

    public Octagon(double side)
    {
      this.side = side;
    }

    public double getSide()
    {
      return side;
    }

    @Override
    public int compareTo(Octagon oct)
    {
      /*
      if (this.getSide()==oct.getSide())
        return 0;
      return this.getSide()>oct.getSide()?1:-1;
      */

      /*
      if(this.getSide()==oct.getSide())
        return 0;
      else if (this.getSide()<oct.getSide())
        return 1;
      else
        return -1;
      */

      /*
      if (this.getSide()>oct.getSide())
        return 1;
      else if (this.getSide() == oct.getSide())
        return 0;
      else
        return -1;
      */

      /*
      if(this.getSide()<oct.getSide())
        return -1;
      else if (this.getSide() == oct.getSide())
        return 0;
      else
        return -1;
      */
      /*
      if(this.getSide()<oct.getSide())
        return -1;
      else if (this.getSide()>oct.getSide())
        return 1;
      else
        return 0;
      */
      /*
      if(this.getSide()>oct.getSide())
        return 1;
      else if (this.getSide()<oct.getSide())
        return -1;
      else
        return 0;
      */
    }
  }

我已经尝试了所有可能的排列来比较两侧,正如您在所有注释掉的块中看到的那样,似乎编译器随机抱怨该方法没有覆盖抽象 compareTo(T o ) Comparable 中的方法有时会在其他时候突然消失。我真的不知道这里发生了什么。感谢任何帮助。

你需要这样:

class Octagon implements Comparable<Octagon>{//Generic allows compiler to have Octagon as param
   @Override
   public int compareTo(Octagon o) {
      return 0;
   }
}

class Octagon implements Comparable{//No generic used. Allows to compare any object(s)
       @Override
       public int compareTo(Object o) {
          return 0;
       }
}