spicy.dll
spicy.dll

Reputation: 957

Does casting an Object array to a String array use the toString() method of the objects?

I need to use the toString() method of an object and put it into an array. I'm wondering, If I cast the array to a String[], will it use the toString() method?

For Example:

public static String[] toStringArray(MyObject[] myObjects) {
    // Will this return the toString() representation of each object?
    return (String[])myObjects;
}

Upvotes: 2

Views: 71

Answers (2)

Steve K
Steve K

Reputation: 4921

The easiest way to do this is:

public static String[] toStringArray(MyObject[] myObjects) {
    return Stream.of(myObjects)
        .map(MyObject::toString)
        .toArray(String[]::new);
}  

Upvotes: 3

Thilo
Thilo

Reputation: 262504

No, it will just fail with a ClassCastException.

Casting does not do any conversion on the object instances. It just checks if it has the type that you want to cast it to.

You may want to look at java.util.Arrays.toString(myObjects) (gives you a String, though, not a String[]).

Upvotes: 6

Related Questions