[英]java.lang.String cannot be cast to Comparable
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: 我有一个自定义的可比接口和一个带有使用该接口的插入方法的对象列表,当我拥有该类的类实现可比接口并在其中具有该方法时,它一直在说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;
}
Here is the comparable interface // comparable.java interface 这是可比接口//可比.java接口
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. 似乎您在定义自己的Comparable接口,而String当然不会实现。 You should use Java's Comparable interface ( http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html ).
您应该使用Java的Comparable接口( http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html )。
Eg this: 例如:
Comparable<String> comparable = (Comparable<String>)(new String());
is perfectly valid piece of code. 是完全有效的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.