java - compareTo 方法不会编译

标签 java interface comparable compareto

我的类(class)标题:

public class GraphEdge implements Comparable<GraphEdge>{

/** Node from which this edge starts*/
protected Point from;
/** Node to which this edge goes*/
protected Point to;
/** Label or cost for this edge*/
protected int cost;

我的 compareTo 方法:

@Override
public int compareTo(GraphEdge other){
    return this.cost-other.cost;
}

但是 Eclipse 给我错误:

GraphEdge 类型的方法 compareTo(GraphEdge) 必须覆盖父类(super class)方法

为什么? 我试着用 Comparable 做

@Override
public int compareTo(Object o){
            GraphEdge other = (GraphEdge) o;
    return this.cost-other.cost;
}

但这也失败了。

最佳答案

您的项目很可能设置为 Java 1.5 合规级别 - 尝试将其设置为 1.6,它应该可以工作。这里没有 Eclipse 来测试,但是我记得当设置为 1.5 时我不能在接口(interface)上使用 @Override(但可以在类上)方法覆盖。这在设置为 1.6 时工作正常。

即当设置为 1.5 时这应该会失败,但在 1.6 时工作正常:

interface A {
   void a();
}

class B implements A {
   @Override
   public void a() {
   }
}

那么试试吧:

enter image description here

关于java - compareTo 方法不会编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9527207/

相关文章:

C++ 为 API 中定义的结构创建父类(super class)

c# - 通过 switch 语句处理对象集合

c# - 何时使用非泛型接口(interface)作为泛型类型约束

java - 找不到符号 - 方法错误

java - 如何避免类似接口(interface)产生的转换错误

java - 简化游戏界面的创建?

java - 在 Eclipse 中从 WSDL 生成 Web 服务 java 类

java.lang.NoSuchMethodException : Unknown property 异常

java - 如何对具有实现相同接口(interface)的不同对象的列表进行排序?

java - selenium 在加载页面后获取当前 url