0

I have a custom comparable interface and a object list with a insert method that uses the interface and it keeps saying that java.lang.String cannot be cast to Comparable when the class that i have it in implements the comparable interface and has the method within the class here's the parts of the code in question:

public class Employee implements Comparable{
private String str1;
private String str2;
private String str3;
private String name;
private int count;
SuperOutput so = new SuperOutput("csis.txt");
ObjectList O2 =  new ObjectList();

public Employee(String e)
{
    name = e;
}

public int compareTo(Object o)
{
    Employee e = (Employee) o;
    return name.compareTo(e.getName());
}
public ObjectList AlphabeticalOrd()
{
    ObjectList ol = new ObjectList();
    ObjectListNode on = new ObjectListNode();
    Employee ep;
    on = O2.getFirstNode();
    Object o;
    so.output("\r\nThese are the employees in alphabetical order");
    while(on != null)
    {
        ObjectListNode s = on;
        //ep = (Employee) s.getInfo();// And this
        o = s.getInfo(); //I have tried using this 
        //System.out.println(O.toString() + "ddddd><<<");
        ol.insert(o);
        on = on.getNext();
    }
    O2 = ol;
    return O2;
}

Here is the comparable interface // comparable.java interface

public interface Comparable {
public int compareTo(Object o);
}

Here is the insert method

  public void insert(Object o) {
    ObjectListNode p = list;
    ObjectListNode q = null;
    while (p != null && ((Comparable)o).compareTo(p.getInfo()) > 0) {
        q = p;
        p = p.getNext();
    }
    if (q == null)
        addFirst(o);
    else
        insertAfter(q, o);
}
2
  • Are you sure you have your Comparable interface imported on all your classes your using it in? You know Java as a verrrryyy similar one in the java.lang package which is automatically imported. Commented Apr 18, 2014 at 4:41
  • yup positive i also just tried renaming it to see if java was being picky Commented Apr 18, 2014 at 4:43

1 Answer 1

1

Seems like you defining your own Comparable interface, which String certainly doesn't implement. You should use Java's Comparable interface (http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html).

E.g. this:

Comparable<String> comparable = (Comparable<String>)(new String());

is perfectly valid piece of code.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer i used the comparable i had ill post how later but will use this in the future but for now the one i have.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.