سؤال

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);
}
هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top