[英]Why Compiler doesn't give error when we assign Integer to int in Java
Why compiler doesn't give error when we assign Integer(object) to int(primitive)? 当我们将Integer(object)赋给int(primitive)时,为什么编译器不会出错?
int i;
Integer ii = new Integer(5);
i = ii;//no compilation error.
And this is the case with all other types(byte-Byte, float-Float).. 所有其他类型(byte-Byte,float-Float)都是这种情况。
What is the reason? 是什么原因? Am i missing something here? 我错过了什么吗?
It's called autoboxing/unboxing. 它被称为autoboxing / unboxing。
As of Java 1.5, the compiler automatically "boxes" primitives into their corresponding class (eg int
and Integer
, double
and Double
etc), and un-boxes as required. 从Java 1.5开始,编译器会自动将基元“装箱”到相应的类中(例如int
和Integer
, double
和Double
等),并根据需要取消框。
See this page in the documentation for more details. 有关详细信息,请参阅文档中的此页面 。
Java SE 5.0 introduced autoboxing as a new feature. Java SE 5.0引入了自动装箱作为新功能。 You can find more information in the Java documentation. 您可以在Java文档中找到更多信息。 http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html
Java 5 and newer are able to perform autoboxing . Java 5及更高版本能够执行自动装箱 。 The compiler will implicitly transform your code into: 编译器将隐式地将您的代码转换为:
int i;
Integer ii = new Integer(5);
i = ii.intValue();
i = ii;//no compilation error.
Because this is called autounboxing. 因为这称为自动装箱。 When you assign object to primitive variable
, value from object is taken out and assigned to primitive. 将object to primitive variable
分配object to primitive variable
,将取出对象的值并将其分配给基元。 this process is called autounboxing
. 此过程称为自动autounboxing
。 Vice versa is Autoboxing
. 反之亦然是Autoboxing
。
This is called "autoboxing/unboxing". 这称为“autoboxing / unboxing”。 The primitive types like int
are automatically converted to classes like Integer
and vice-versa when it is needed. 像int
这样的基本类型会在需要时自动转换为类似Integer
类,反之亦然。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.