Home  >  Article  >  Java  >  In-depth analysis of java automatic boxing and unboxing

In-depth analysis of java automatic boxing and unboxing

高洛峰
高洛峰Original
2017-01-24 14:16:011531browse

This is a new content introduced after jdk1.5. As I insist that publishing is the best memory, I decided to replace my memory with a blog:
The Java language specification says: In many cases Packaging and unpacking are done by the compiler itself (in this case, packaging is called boxing, and unpacking is called unboxing);
In fact, according to my own understanding, automatic boxing can be simply understood as Basic data types are encapsulated into object types to comply with Java's object orientation; for example, use int as an example:

//声明一个Integer对象 
Integer num = 10; 
//以上的声明就是用到了自动的装箱:解析为 
Integer num = new Integer(10);以上就是一个很好的体现,因为10是属于基本数据类型的,原则上它是不能直接赋值给一个对象Integer的,但jdk1.5后你就可以进行这样的声明,这就是自动装箱的魅力 
自动将基本数据类型转化为对应的封装类型。成为一个对象以后就可以调用对象所声明的所有的方法 
自动拆箱:故名思议就是将对象重新转化为基本数据类型: 
//装箱 
Integer num = 10; 
//拆箱 
int num1 = num;自动拆箱有个很典型的用法就是在进行运算的时候:因为对象时不恩直接进行运算的,而是要转化为基本数据类型后才能进行加减乘除 
Integer num = 10; 
//进行计算时隐含的有自动拆箱 
System.out.print(num--);哈哈 应该感觉很简单吧,下面我再来讲点稍微难点的, 
//在-128~127 之外的数 
Integer num1 = 297; Integer num2 = 297; 
System.out.println("num1==num2: "+(num1==num2)); 
// 在-128~127 之内的数 
Integer num3 = 97; Integer num4 = 97; 
System.out.println("num3==num4: "+(num3==num4)); 打印的结果是:num1==num2: false num3==num4: true

It's strange: this is due to Java's design of automatic boxing and unboxing of Integer and int , is a mode: called flyweight mode (flyweight)
In order to increase the reuse of simple numbers, java defines: During automatic boxing, for values ​​​​from –128 to 127, they are boxed After being an Integer object, it will be stored in the memory and be reused. There will always be only one object
And if it exceeds the value from –128 to 127, the boxed Integer object will not be reused, which is equivalent to A new Integer object is created every time it is boxed; you understand
The above phenomenon is caused by the use of automatic boxing. If you do not use automatic boxing, but use new like a general class. Instantiation will create a new object every time new is created;
This automatic boxing and unboxing is not only used in basic data types, but also in the String class. For example, when we often declare a String object:

String str = "sl"; 
//代替下面的声明方式 
String str = new String("sl");

Autoboxing and unboxing of basic data (Primitive) types are functions provided since J2SE 5.0. Although it provides convenience for you to package basic data types, it also hides the details. It is recommended to use it only when you can distinguish the difference between basic data types and objects.
autoboxing and unboxing
In Java, almost everything to be processed is an object (Object). For example, the Scanner used before is an object, and the string (String) is also an object. You will see more later Object. However, basic data types are not objects, that is, variables you define using int, double, boolean, etc., and literal constants you write directly in.
In the previous section, we have roughly seen the convenience of operating objects, and anyone who has used Java for a while knows that sometimes it is necessary to convert basic data types into objects. For example, when using the put() method of a Map object, the parameters that need to be passed in are objects rather than basic data types.
You need to use wrapper types (Wrapper Types) to wrap basic data types into objects. In the previous section, you already know that before J2SE 5.0, you need to use the following statement to wrap int into an Integer object: Integer integer = new Integer (10);
The automatic boxing function is provided after J2SE 5.0. You can directly use the following statement to package basic data types: Integer integer = 10;
When compiling, the compiler will automatically Write the statement to determine whether to perform automatic boxing action. In the above example, integer refers to an instance of the Integer class. The same action can be applied to basic data types such as boolean, byte, short, char, long, float, double, etc., and the corresponding wrapper types (Wrapper Types) Boolean, Byte, Short, Character, Long, Float or Double will be used respectively. Let's directly use the autoboxing function to rewrite Example 4.4.

Example 4.5 AutoBoxDemo.java

public class AutoBoxDemo { 
public static void main(String[] args) { 
Integer data1 = 10; 
Integer data2 = 20; 
// 转为double值再除以3 
System.out.println(data1.doubleValue() / 3); 
// 进行两个值的比较 
System.out.println(data1.compareTo(data2)); 
} 
}

The program seems much simpler. data1 and data2 are instances of Integer at runtime and can directly perform object operations. The result is as follows:
3.3333333333333335
–1
The method of using automatic boxing can also be as follows:

int i = 10; 
Integer integer = i;

You can also use the more general java.lang.Number class to automatically box . For example:
Number number = 3.14f;
3.14f will be automatically boxed as Float first and then assigned to number.
Starting from J2SE 5.0, automatic boxing and automatic unboxing are available, that is, the basic data form information in the object is automatically taken out of the object. For example, it is possible to write as follows:

Integer fooInteger = 10; 
int fooPrimitive = fooInteger;

After fooInteger is referenced to an instance that is automatically boxed as Integer, if it is assigned to an int type variable fooPrimitive, it will automatically become int type and then assigned to fooPrimitive. During operation, automatic boxing and unboxing can also be performed. For example:

Integer i = 10; 
System.out.println(i + 10); 
System.out.println(i++);

In the above example, 20 and 10 will be displayed. The compiler will automatically perform automatic boxing and unboxing, that is, 10 will be boxed first, and then unboxed first when i + 10. Perform addition operation; i++ line also unboxes first and then performs increment operation. Let’s look at another example:

Boolean boo = true; 
System.out.println(boo && false);

同样的boo原来是Boolean的实例,在进行AND运算时,会先将boo拆箱,再与false进行AND运算,结果会显示false。 
////////////////////////////////////////////////////////////////// 
装箱:从基本类型转换成Object类型,称之为装箱;***拆箱:从Object转换乘基本类型的操作,称之为拆箱。 这个操作在反射过程中用的比较的多。 
装箱:在堆中建立一个Object实例,把你指定的值复制成去;***拆箱:判别引用指向的堆中信息是否是要拆成的类型,是取出堆中值送给栈中变量,否则报异常 
/////////////////////////////////////////////////////////////////// 
装箱是值类型到object类型或到该值类型所实现的任何接口类型的隐士转换。 
将一个值类型装箱会分配一个对象实例并将该值复制到新的对象中。 

int i=123; 
object o=i;

这句话的结果是在堆栈上创建一个对象o,而该对象在堆上引用int类型的值。该值是赋值给变量i 
的值类型值的一个副本。 
下面是显示执行装箱转换 

int i=123; 
ojbect o=(object)i;

此例将整数变量i通过装箱转换为对象o。这样,存储在变量i中的值就从123改为456。此例显示对象保留了内容的原始副本。即123。 
取消装箱是从object类型到值类型或从接口类型到实现该接口的值类型的显示转换。取消装箱操作包括: 
检查对象实例,确保它是给定值类型的一个装箱值。 
将该值从实例复制到值类型变量中。 
例子: 

int i=123; 
object box=i; 
int j=(int)box;

更多java自动装箱拆箱深入剖析相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn