Box packing and unpacking

Source: Internet
Author: User

Packing and unpacking what is the box and unboxing description

Language description, boxing is the automatic conversion of the basic data type to the wrapper type; unpacking is the automatic conversion of the wrapper type to the base data type.

The code description is:

    Integer integer = 100;  //自动装箱    int i = integer;  //自动拆箱
The wrapper type table for the basic technology type:
Data Type Wrapper Type
Int (4 bytes) Integer
Byte (1 bytes) Byte
Short (2 bytes) Short
Long (8 bytes) Long
Float (4 bytes) Float
Double (8 bytes) Double
Char (2 bytes) Character
Boolean (Undecided) Boolean
How to implement packing and unpacking code for crates and unboxing
public class IntegerAndInt {    public static void main(String[] args) {        // TODO Auto-generated method stub        Integer integer = 100; //自动装箱        int i = integer; //自动拆箱    }}
Decompile the class file


The valueof (int) method of the integer is automatically called when boxing, as can be seen from the content of the bytecode obtained from the decompile. The Intvalue method of integer is called automatically when unpacking.

Therefore, the boxing process is implemented by calling the wrapper's ValueOf method, and the unboxing process is implemented by calling the wrapper's Xxxvalue method.

ValueOf method
 public static Integer valueOf(int i) {     return  i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128]; }

The numeric value is determined first, if the value is greater than or equal to 128 or less than-128, an integer object is created to return, otherwise the value of Small_values's i+128 is returned.

Next, look at the constructor for the following integer:

private final int value;public Integer(int value) {    this.value = value;}public Integer(String string) throws NumberFormatException {    this(parseInt(string));}

The integer defines a value variable, which initializes the variable when an integer object is created. The second passed in is a string variable, which first converts it to an int value and then initializes it.

Take a look at small_values[i+128]:

private static final Integer[] SMALL_VALUES = new Integer[256];

Small_values is a static integer array object, which means that valueof returns an integer object.
Analysis can see that the boxing process will create the corresponding object, this will consume memory, so the boxing process will increase memory consumption, affect performance.

InitValue method
 @Override public int intValue() {     return value; }

The Intvalue method returns the value values directly.

Example of some problems needing attention in packing and unpacking
public class Main{    public static void main(String[] args) {        Integer i1 = 66, i2 = 66, i3 = 166, i4 = 166;        System.out.println(i1 == i2);//true        System.out.println(i3 == i4);//false       }}

Look at the above code can be found that the results of the two comparisons are not the same, and then combined with the above boxing principle, 128~-127 boxing is directly returned to the small_values array stored in the value, so i1 and I2 boxing results are returned the same variable, so is equal, While i3 and I4 are the newly created variables that are returned, two variables are different, so they are not equal.

Example Two
Integer a = new Integer(6);Integer b = 6; // 将6自动装箱成Integer类型int c = 6;System.out.println(a == b); // false 两个引用没有引用同一对象System.out.println(a == c); // true a自动拆箱成int类型再和c比较

A is an integer object created, and B is automatically boxed, which is the value stored in the small_values array, so A and B are different objects, not equal, and C is the value of type int, and A and C are equal to the 6, two 6 values of the type int.

Example Three
    Integer i1 = new Integer(6);    Integer i2 = 6;    System.out.println("i1.equals(i2):"+(i1.equals(i2))); //true

Will find the same object, = = and equals the result is different, first look at the equals source:

 @Override public boolean equals(Object o) {     return (o instanceof Integer) && (((Integer) o).value == value); }

The Equals method is found to compare the value of the same, comparing the contents of itself.

Example Four
Integer num1 = 100;int num2 = 100;Long num3 = 200L;System.out.println(num1+num2); //200System.out.println(num3 == (num1+num2)); //trueSystem.out.println(num3.equals(num1+num2)); //falseSystem.out.println(num3 == (num1+num2)); //true

When a basic type data domain encapsulates a class for = =, + 、-、 *,//operations, the wrapper class is disassembled and the underlying data type is calculated.
The reason Num3.equals (NUM1+NUM2) is false is that the type of num1+num2 is not a long, so it is false.
The Equals method of long:

 @Override public boolean equals(Object o) {     return (o instanceof Long) && (((Long) o).value == value); }

while (NUM3 (NUM1+NUM2)) is true, when the two operands of an operator are references to the wrapper type, the comparison is to whether the same object is being compared, and if one of the operands is an expression (that is, it contains arithmetic operations), the value is compared (that is, the process that triggers the automatic unboxing).

Example Five
  Integer integer=null;  int i=integer;

The above code can be compiled, but at run time, a null pointer exception is thrown. Integer is the integer type of the choice of love, can point to null, but when the integer is unboxing, is to call a null object valueof, so throws a null pointer exception.

Attention

Integer, short, Byte, Charater, long these classes of valueof method implementation is similar, double and float valueof method implementation is similar, is not like an integer Small_ Value of the array.
Double the valueof method:

public static Double valueOf(double d) {    return new Double(d);}

Float's ValueOf method:

public static Float valueOf(String s) throws NumberFormatException {    return new Float(FloatingDecimal.getThreadLocalInstance().readJavaFormatString(s).floatValue());}

Also, the Boolean valueof method:

public static Boolean valueOf(boolean b) {    return (b ? TRUE : FALSE);}

So, regardless of whether the object is the same, as long as the value of the object is the same, it is equal.

5. Summary

Java's automatic boxing and unpacking mechanism saves some memory overhead and the overhead of creating objects (the 128~-127 common value of integer saves money), improves efficiency and simplifies the code without requiring the programmer to convert the type every time. Use the Equals () method as much as possible when comparing values equal.

Reference articles

Https://www.cnblogs.com/wang-yaz/p/8516151.html detailed Java automatic packing and unpacking (autoboxing and unboxing)
Https://www.cnblogs.com/dolphin0520/p/3780005.html in-depth analysis of boxing and unpacking in Java

Box packing and unpacking

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.