我在下面的代码中收到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
最佳答案
如 javadoc所述:
ClassCastException-如果指定对象的类型阻止将其与该对象进行比较。
看来您的compareTo
是target
类型的String
,并且Comparable<String>
返回的是current.getValue()
类型的对象。
您可以尝试执行Integer
,如果它正常,那么我是对的。 :)