简体   繁体   English

Java装箱或拆箱

[英]Java boxing or unboxing

I found an example where I cannot find the number of boxing and unboxing in the Java code below : 我找到了一个示例,在下面的Java代码中找不到装箱和拆箱的数量:

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

I would say that there is one type of unboxing ( int y = x + x ), but I am not sure about that. 我会说这是一种拆箱( int y = x + x ),但是我不确定。 Is there any boxing as well? 还有拳击吗?

There is one boxing in Integer x = 5 . Integer x = 5有一个拳击。 The int 5 is boxed to Integer . int 5装箱为Integer

There are two un-boxings in int y = x + x : Integer x is unboxed twice. int y = x + x有两个取消装箱操作:将Integer x取消装箱两次。

There is only boxing 只有拳击

Integer x = 5

From Docs: 从文档中:

If p is a value of type int, then boxing conversion converts p into a reference r of class and type Integer, such that r.intValue() == p 如果p是int类型的值,则装箱转换将p转换为类和Integer类型的引用r,这样r.intValue()== p

Why? 为什么? Because we are reference only once And there are two unboxing in : 因为我们仅引用一次,所以在其中有两个拆箱:

int y = x + x

From Docs 从文档

If r is a reference of type Integer, then unboxing conversion converts r into r.intValue() 如果r是Integer类型的引用,则取消装箱转换会将r转换为r.intValue()

Why? 为什么? Because we are calling two times x.IntValue() 因为我们两次调用x.IntValue()

Following this docs from Boxing and Unboxing 遵循装箱和拆箱中的此文档

Change values from Primitive value to Wrapper Class Values in java example 在Java示例中将值从原始值更改为包装器类值

Integer a = 10;
int b = a;

https://youtu.be/96pq0mpFz9M https://youtu.be/96pq0mpFz9M

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

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