简体   繁体   中英

Implicit conversion from primitive type to Object

Here is this code:

int[] someArray = {0, 1, 2, 3};
//System.out.println(someArray[0].toString()); int cannot be dereferenced
// creating Object element with use of primitive element fails
//Object newObject = new Object(someArray[0]); constructor Object in class java.lang.Object cannot be applied to given types;
for(Object someObject : someArray)
{
    // here int is casted to Object
    System.out.println(someObject.toString()); // prints 0, 1, 2, 3
}

How does it happen that primitive type variable (element of array) cannot be explicitly casted to Object, however somehow in for loop this primitive element is casted to Object?

Since 1.5, the Java compiler will automatically box and unbox primitive types when the context calls for it. (That is, an int gets wrapped in an Integer object and vice versa.) This happens when assigning between a primitive and an object variable. (Or casting a primitive to an object type.) So, for example, the following code is valid:

int i = 123;
Object o = i;

The same goes for the implicit assignment Object someInt = someArray[…] that the compiler emits for the foreach loop.

The reason why someArray[0].toString() doesn't work is that you're not assigning someArray[0] to an object typed variable or doing anything else that would tell the compiler to autobox – trying to call a method on a primitive simply isn't recognized as one of the conditions when this should occur.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM