简体   繁体   English

在 Java 中直接将原始类型转换为 object 可以吗?

[英]Directly casting primitive type to object is fine in Java?

I am directly casting my int primitive type variable to Integer object like below:我直接将我的 int 原始类型变量转换为 Integer object 如下所示:

int intValue = 0;
Integer value = (Integer) intValue;

Is this fine or will cause some unexpected problems?这很好还是会导致一些意想不到的问题?

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.自动装箱是 Java 编译器在原始类型与其对应的 object 包装类之间进行的自动转换。

int intValue = 0;
Integer value = intValue; // by Autoboxing

you can also convert it using valueOf method of wrapper class您也可以使用包装器 class 的 valueOf 方法对其进行转换

Integer value = Integer.valueOf(intValue)

Check What code does the compiler generate for autoboxing?检查编译器为自动装箱生成哪些代码? if you still have doubts.如果您仍有疑问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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