404 Brain Not Found
404 Brain Not Found

Reputation: 605

Casting from Object to Object[]

I was going though a part of my code, in which I had to explicitly type-case different data types into object type and vice versa, when I couldn't make sense of how something like this is done :

(Object[])obj; //Casting an Object variable into and Object[]

I have tried to do the same with every other built-in and primitives. It does not work.

(String[])str; //Gives the error cannot cast from string to string[]

(int[])i; //Gives the error cannot cast from int to int[]

(char[])ch; //Gives the error cannot cast from char to char[]

(long[])l; //Gives the error cannot cast from long to long[]

(Integer[])in; //Gives the error cannot cast from int to Integer[]

where str is a of type string, i and in are of type int, ch is of type char, l is of type long.

Then how is it allowed, and internally how is it accomplished when we do (Object[])obj;?

Here obj is of type Object

Upvotes: 1

Views: 407

Answers (1)

GhostCat
GhostCat

Reputation: 140427

Any instance of a refence type is also an Object.

Arrays for example.

An array of String... is an Object.

An array of Object... is an Object.

Therefore, when the actual object is such an array, you can cast back.

But: an array of string is never a string. Therefore that cast does not work!

In code:

String[] strings = { "a", "b", "c" };
Object obj = strings;

That second line works because anything that is "an object", can assigned to an Object variable. And because obj is actually referencing a string array, you can then cast back:

String[] anotherVariablePointingToTheSameArray = (String[]) obj;

Keep in mind: that cast has only one meaning: you know better than the compiler. You know that "something" is actually (at runtime) more specific.

In other words: you can only do a (X) y cast if y instanceOf(X) would return true!

Upvotes: 4

Related Questions