2013-10-30 35 views
3

我可能是很愚蠢的,但它讓我瘋狂。我搜查了一下,但是對於編程來說相對較新,而且在我頭腦中。如果可以的話請幫忙! bar參數是一個arraylist.toArray(),它只是充滿了字符串。我可以將對象轉換爲字符串的對象數組中的字符串。獲得classCastException

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); 
} 
+0

是不是'ArrayList '?另外,發佈完整的堆棧跟蹤。 –

+0

這不是,但下面的答案是完美的。我將在以後 – juju

回答

6

做到這一點,而不是

String s = String.valueOf(o); 

你不能,如果它不是一個String對象對象強制轉換爲字符串。您需要在對象上調用toString方法 - 除非對象是nullString.valueOf()需要照顧

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

感謝人發佈堆棧跟蹤。那很完美。 – juju