我在下面的代码中遇到了 ClassCastException,这对我来说没有多大意义,因为 targetObject
是一个 Comparable,而 current
是一个 ToBeFound。整数和字符串从哪里来?
ToBeFound origin = new ToBeFound();
public ToBeFound findWrapper(Comparable targetObject)
{
return find(origin, targetObject);
}
private ToBeFound find(ToBeFound current, Comparable targetObject)
{
if (current == null)
{
return null;
}
System.out.println(targetObject.compareTo(current.getValue()));
// Exception in thread "main" java.lang.ClassCastException:
// java.lang.Integer cannot be cast to java.lang.String
return new ToBeFound();
}
//body of main() that calls the methods
master.find( (Comparable) scanner.next());
// Scanner is a java.util.Scanner scanning System.in
最佳答案
如compareTo
javadoc 指出:
ClassCastException - if the specified object's type prevents it from being compared to this object.
看来你的target
是 String
类型为Comparable<String>
和current.getValue()
返回 Integer
的对象类型。
你可以尝试做String.valueOf(current.getValue)
如果它工作正常那么我是对的。 :)
关于java - Java 中的 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5256497/