0

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.

9
  • 5
    You're not casting from Object[] to String[]. You're casting from Object[][] to String[] Commented Jul 12, 2016 at 20:56
  • 3
    The first example works because an Object[] is an Object (everything is an Object). Commented Jul 12, 2016 at 20:58
  • 1
    Please explain why you want to cast arrays of different dimension. This is obviously not very meaningful. Commented Jul 12, 2016 at 20:59
  • 1
    You can't make a 2-dimensional array into a 1-dimensional array. Commented Jul 12, 2016 at 20:59
  • 1
    An Object[] is not necessarily one-dimensional. It could be any dimension you like. An Object[][][][][] is an Object, so your Object[] can contain several Object[][][][][], making it six-dimensional. Commented Jul 12, 2016 at 21:22

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.