开发者

Implementing Comparable in java 1.4.2

开发者 https://www.devze.com 2023-03-02 04:42 出处:网络
I have a Java question. I\'m trying to implement Comparable in my class.Based on my research, the statement for my class would be:

I have a Java question. I'm trying to implement Comparable in my class. Based on my research, the statement for my class would be:

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. I believe this is because I'm stuck with java 1.4.2 (yes, it's sadly true).

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 is not abstract and does not override abstrac开发者_高级运维t 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? 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. It is OK to do so without checking the type of other, as compareTo declares that it can throw ClassCastException (caller beware).


Your compareTo() method should take Object and then you should cast it to ProEItem inside the method.`

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


compareTo takes Object as a parameter in 1.4.2

e.g.

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

精彩评论

暂无评论...
验证码 换一张
取 消