[英]Implementing Comparable in java 1.4.2
I have a Java question.我有一个 Java 问题。 I'm trying to implement Comparable in my class.我正在尝试在我的 class 中实现 Comparable。 Based on my research, the statement for my class would be:根据我的研究,我的 class 的声明将是:
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
However, I get the compile error that { is expected after Comparable in the class declaration.但是,在 class 声明中的 Comparable 之后出现 { 是预期的编译错误。 I believe this is because I'm stuck with java 1.4.2 (yes, it's sadly true).我相信这是因为我坚持使用 java 1.4.2(是的,可悲的是真的)。
So I tried this:所以我尝试了这个:
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
Without the ProEItem after comparable, but then my compile error is this:比较后没有ProEItem,但是我的编译错误是这样的:
"ProEItem is not abstract and does not override abstract method compareTo(java.lang.Object) in java.lang.Comparable
public class ProEItem implements Comparable {"
So my question is what am I doing wrong to implement comparable in 1.4.2?所以我的问题是在 1.4.2 中实现可比性我做错了什么? Thank you.谢谢你。
It should be declared应该声明
public int compareTo(Object other)
You then have to down-cast the other
object to your type, ProEItem
and do the comparison.然后,您必须将other
object 向下转换为您的类型ProEItem
并进行比较。 It is OK to do so without checking the type of other
, as compareTo
declares that it can throw ClassCastException
(caller beware).这样做可以不检查other
的类型,因为compareTo
声明它可以抛出ClassCastException
(调用者要小心)。
Your compareTo() method should take Object and then you should cast it to ProEItem inside the method.`您的 compareTo() 方法应采用 Object ,然后您应将其转换为方法内的 ProEItem。
public int compareTo(Object other) {
return this.getName().compareTo(((ProEItem)other).getName());
}
compareTo
takes Object
as a parameter in 1.4.2 compareTo
在 1.4.2 中以Object
作为参数
eg例如
public int compareTo(Object other) {
return this.getName().compareTo(other.getName());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.