user1365914
user1365914

Reputation: 888

Java casting Object/String arrays

I'm playing with Java to see how it works but I have some doubts about some kind of castings. Consider the following piece of code:

String[][] s = null;
Object[] o = null;

o = (Object[][]) s; // compile-time correct

Now, consider the following example:

Object[][] o = null;
String[] s = null;

s = (String[]) o; // compile-time error: Cannot cast from Object[] to String[]

Why does that happen? I'm confused.

Upvotes: 0

Views: 66

Answers (2)

Taylor
Taylor

Reputation: 4087

It's failing because it's deterministically (i.e. always and can only ever be) wrong.

o necessarily contains arrays of objects. These can NEVER be Strings.

The first sample you have, a String array can be typed as an object.

We can illustrate this if we remove an "array nesting". Consider:

String[] myStringArray = null;  //instantiation not important
Object someObj = myStringArray; //no problem since arrays are Objects

What you're doing in the second example amounts to

Object[] myObjectArray = null;  //instantiation not important
String someString = myObjectArray; //compile time error, since an Object[] is never a String

Upvotes: 1

Steven Whaley
Steven Whaley

Reputation: 109

Notice that this doesn't give your compile error:

Object[] o = null;
String[] s = null;

s = (String[]) o;

Object[][] to String[] will give incompatible type error.
Object[] to String[] will work normally.

Upvotes: 2

Related Questions