簡體   English   中英

java.lang.String不能強制轉換為Comparable

[英]java.lang.String cannot be cast to Comparable

我有一個自定義的可比接口和一個帶有使用該接口的插入方法的對象列表,當我擁有該類的類實現可比接口並在其中具有該方法時,它一直在說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;
}

這是可比接口//可比.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);
}

似乎您在定義自己的Comparable接口,而String當然不會實現。 您應該使用Java的Comparable接口( http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html )。

例如:

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

是完全有效的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM