[英]Can I cast an object to a string from an object array of strings. Getting classCastException
我可能很傻,但它讓我瘋了。 我已經四處尋找,但我對編程比較陌生,而且我已經掌控了。 如果可以的話請幫忙! 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);
如果Object不是String對象,則不能將Object強制轉換為String。 您需要在對象上調用toString
方法 - 除非該對象為null
。 String.valueOf()
處理這個問題
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.