Search code examples
javaclasscomparable

Implementing Comparable in java 1.4.2


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 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? Thank you.


Solution

  • 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());
            }