java.lang.String无法强制转换为Comparable

时间:2014-04-18 04:18:09

标签: java string casting comparable

我有一个自定义的可比较的接口和一个带有insert方法的对象列表,该方法使用了接口,并且它一直说java.lang.String在我拥有它的类实现类似的接口时不能强制转换为Comparable这里的方法是有问题的代码部分:

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;
}

这是可比较的界面 // comparative.java接口

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

这是插入方法

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

1 个答案:

答案 0 :(得分:1)

好像你定义了自己的Comparable接口,String当然没有实现。您应该使用Java的Comparable接口(http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html)。

E.g。这样:

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

是完全有效的代码。