包装和Java中的自动装箱/拆箱有什么区别?

abh*_*kar 0 java boxing unboxing

Wrapper类用于将原始进入对象和对象转换为原始。类似地,通过使用AutoboxingUnboxing我们可以做相同的事情,那么这两者有什么区别:1-概念明智2-代码明智???

And*_*eas 6

自动装箱和自动拆箱只是编译器在无声地帮助您创建和使用原始包装对象的情况。

例如,int原始类型的包装类称为Integer。您包装和展开,如下所示:

int myInt = 7;

// Wrap the primitive value
Integer myWrappedInt = Integer.valueOf(myInt);

// Unwrap the value
int myOtherInt = myWrappedInt.intValue();
Run Code Online (Sandbox Code Playgroud)

使用自动装箱和自动拆箱,您不必做所有的样板工作:

int myInt = 7;

// Wrap the primitive value
Integer myWrappedInt = myInt; // Compiler auto-boxes

// Unwrap the value
int myOtherInt = myWrappedInt; // Compiler auto-unboxes
Run Code Online (Sandbox Code Playgroud)

它只是语法糖,由编译器处理。生成的字节码相同。