gpt4 book ai didi

java - 我可以将对象从字符串对象数组转换为字符串吗?获取 classCastException

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:47:52 25 4
gpt4 key购买 nike

我可能很傻,但这让我抓狂。我四处搜索,但对编程还比较陌生,而且我不知所措。如果可以的话请帮忙! bar 参数采用 arraylist.toArray() 并且它只是充满了字符串。

public bar(Object[] contents) {

for (Object o : contents) {
String s = (String) o;
if (s == null) {
System.out.println("newline"); //checking
} else {
try {
arrayContents.add(new line(s));

} catch (Exception ex) {
System.out.println("error printing note: " + s + " " + ex + " in bar " + i);
}
}
i++;

}
// System.out.println(arrayContents);
}

最佳答案

改为这样做

    String s = String.valueOf(o);

如果对象不是字符串对象,则不能将其转换为字符串。您需要改为在对象上调用 toString 方法 - 除非对象为 nullString.valueOf() 会处理这个问题

public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}

关于java - 我可以将对象从字符串对象数组转换为字符串吗?获取 classCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19694129/

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