2011-04-29 42 views
0

我有一个Java问题。 我试图在我的课程中实现Comparable。根据我的研究,我的课的声明将是:在java 1.4.2中实现Comparable

public class ProEItem implements Comparable<ProEItem> { 
    private String name; 
    private String description; 
    private String material; 
    private int bomQty; 

// other fields, constructors, getters, & setters redacted 

    public int compareTo(ProEItem other) { 
     return this.getName().compareTo(other.getName()); 
     } 
}// end class ProEItem 

但是,我得到的编译错误{之后在类声明可比的预期。我相信这是因为我与Java 1.4.2卡住(是的,这是可悲的)。

所以,我想这一点:

public class ProEItem implements Comparable { 
     private String name; 
     private String description; 
     private String material; 
     private int bomQty; 

    // other fields, constructors, getters, & setters redacted 

     public int compareTo(ProEItem other) { 
      return this.getName().compareTo(other.getName()); 
      } 
    }// end class ProEItem 

后无可比性的ProEItem,但后来我的编译错误是这样的:

"ProEItem is not abstract and does not override abstract method compareTo(java.lang.Object) in java.lang.Comparable 
public class ProEItem implements Comparable {" 

所以我的问题是什么我做错了实现可比1.4.2? 谢谢。

+0

我鼓励你的系统团队让你升级。即使是Java 5,近2年来也没有得到支持。我知道这并不能解决眼前的问题。 – corsiKa 2011-04-29 17:31:26

回答

1

你的compareTo()方法应采取的对象,然后你要抛弃它的method.`

public int compareTo(Object other) { 
     return this.getName().compareTo(((ProEItem)other).getName()); 
     } 
+0

谢谢,Kal!这工作完美。 – lkb3 2011-04-29 17:32:10

0

compareTo需要Object作为参数1.4.2

例如

public int compareTo(Object other) { 
      return this.getName().compareTo(other.getName()); 
} 
2

应宣布里面ProEItem

public int compareTo(Object other) 

然后,您必须将other对象向下投射到您的类型ProEItem并进行比较。没有检查other的类型,可以这样做,因为compareTo声明它可以抛出ClassCastException(主叫方当心)。