gpt4 book ai didi

java - Java 中的 ClassCastException

转载 作者:行者123 更新时间:2023-12-01 15:54:59 25 4
gpt4 key购买 nike

我在下面的代码中遇到了 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.

看来你的targetString类型为Comparable<String>current.getValue()返回 Integer 的对象类型。

你可以尝试做String.valueOf(current.getValue)如果它工作正常那么我是对的。 :)

关于java - Java 中的 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5256497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com