Saturday, March 20, 2010

You can't cast Object[] to String[] in Java

Consider this snippet:
String[] str = (String[]) new Object[] { "Bla!"};.
That gives a ClassCastException. The short version of an explanation: an array instantiated by new Object[] is of a different class than one by new String[]. For the full glory of that fact, please see the Java Language Specification. As a teaser, I'll quote this snippet and its output from it:

class Test {
public static void main(String[] args) {
int[] ia = new int[3];
System.out.println(ia.getClass());
System.out.println(ia.getClass().getSuperclass());
}
}

which prints:
class [I
class java.lang.Object.

1 comment:

  1. Of course, this can not work with static typing.

    What's funny is even if String[] and Object[] are two different types, the JLS permits to downcast String[] to Object[], even though it's unsafe. But the opposite is forbidden as you experienced.

    With generic lists, both operations are forbidden.

    See http://stackoverflow.com/questions/2442337/common-ancestor-to-java-array-and-list/2442414#2442414

    But C# has better support of co- and contra-variance, so you can do something conceptually like:

    Iterator[Object] iter = new ArrayList[String]();

    which is unsafe only if you add an Object. If the downcast is read-only like in the case of an iterator it's safe.

    ReplyDelete

Note: Only a member of this blog may post a comment.