Java:实现 Comparable 接口(interface)的问题

标签 java interface comparable

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

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;
      */
    }
  }

我已经尝试了所有可能的排列来比较两侧,正如您在所有注释掉的 block 中看到的那样,编译器似乎随机提示该方法没有覆盖抽象的compareTo(T o)方法有时可以比较,但有时却突然不行。我真的不知道这是怎么回事。如有任何帮助,我们将不胜感激。

最佳答案

你需要这样:

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;
       }
}

关于Java:实现 Comparable 接口(interface)的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32643686/

相关文章:

java - 如何让 Geany 回到窗口状态

java - 带有 setBigDecimal 参数的 Java preparedStatement 引发 ORA-03115

Java内置类到接口(interface)

c - 如何用C语言设计嵌入式软件应用库接口(interface)的通用向后兼容API?

c# - 在接口(interface)中定义类实现

java - 在泛型集合中实现 remove(Object o)

java - 从文件中删除一行

java - 如何使用 ActiveJDBC 处理与数据库的重新连接

java - 为什么我无法对这个 ArrayList 进行排序?

java - compareTo 错误 比较方法违反了其一般契约