juju
juju

Reputation: 555

Can I cast an object to a string from an object array of strings. Getting classCastException

I'm probably being very silly, but it's driving me nuts. I have searched around but am relatively new to programming and am in over my head. Please help if you can! the bar parameter is taking an arraylist.toArray() and it's just full of strings.

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

Upvotes: 3

Views: 95

Answers (1)

ZhongYu
ZhongYu

Reputation: 19682

Do this instead

    String s = String.valueOf(o);

You cannot cast an Object to String if it is not a String object. You'll need to invoke toString method on the object instead - unless the object is null. String.valueOf() takes care of that

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

Upvotes: 6

Related Questions