简体   繁体   English

Java装箱和拆箱

[英]Java boxing and unboxing

I have an example in which I cannot determine the number of boxing(s) and unboxing(s), which taking place in the Java code below : 我有一个示例,其中我无法确定装箱和拆箱的数量,这些情况发生在以下Java代码中:

int x = 5;
Integer y = x + x;

From my point of view I see one type of boxing (Integer y = x + x). 从我的角度来看,我看到一种拳击类型(整数y = x + x)。 Am I wrong? 我错了吗? Is there any unboxing as well? 还要取消装箱吗?

There is no unboxing . 没有拆箱 Just boxing happening. 刚发生拳击

First the expression x+x calculated which is an int and that is boxed to Integer . 首先计算表达式x+x ,它是一个int ,并Integer

So in the whole statement there is no conversion of Integer to int , hence no unboxing . 因此,在整个语句中,没有将Integer转换为int ,因此没有拆箱

As per your question we first define an int value and assign it to x variable (no boxing un-boxing required), Then you are adding 2 integer variable no boxing un-boxing required. 根据您的问题,我们首先定义一个int值并将其分配给x变量(无需装箱取消装箱),然后添加2个整数变量,无需装箱取消装箱。 Now you are assigning a int result to Integer means changing from primitive to non primitive data type. 现在,您将一个int结果分配给Integer意味着从原始类型更改为非原始数据类型。 Java autoboxing can convert int to integer there here autoboxing is there which is boxing. Java自动装箱可以将int转换为整数,这里自动装箱就是装箱。

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

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