I encountered with question: why it's impossible cast int[]
to object[]
, e.g.
object[] o = new int[] { 0, 1, 2 };
Meanwhile I can cast to just object
and back to int[]
.
I'll be glad to hear deep answer.
If your object is a String , then you can use the Integer. valueOf() method to convert it into a simple int : int i = Integer. valueOf((String) object);
A Java object is a member (also called an instance) of a Java class. Each object has an identity, a behavior and a state. The state of an object is stored in fields (variables), while methods (functions) display the object's behavior. Objects are created at runtime from templates, which are also known as classes.
Type Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind of Object, and the process of conversion from one type to another is called Type Casting.
Directly from the docs:
Array covariance specifically does not extend to arrays of value-types. For example, no conversion exists that permits an int[] to be treated as an object[].
An array of ints or any other value-type is not an array of objects. Value types have different storage characteristics to those of reference types. An array of (reference type) objects holds a list of object references (with the objects themselves living in the heap), so the slots will always be a constant width. Value types, on the other hand, store their value directly in the array, so the slots might be any width. This makes a conversion between the two meaningless.
It's a little confusing because even though value-types are derived from System.Object, they behave very differently to reference types, and object-like behaviour of value types (e.g. boxing) is only possible through magical handling of them by the compiler and runtime, and it doesn't extend to arrays.
As a side note, casting arrays is a well dodgy practice. I wouldn't do it.
For an instance of type A
to be castable to type B
, one of the following conditions must be true:
A
to B
;A
from B
(e.g., class A : B {}
)string[]
> object[]
) (*)
IEnumerable<string>
> IEnumerable<object>
and Func<string>
> Func<object>
)string Method() {}
can be assigned to delegate object Del();
)You cannot cast int[]
to object[]
because none of the above conditions are true.
(*) - You should avoid this though - array covariance is broken and was it was added simply so that the CLR would support Java-like languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With