Knowledge summary of Java wrapper class, automatic boxing and unpacking

Source: Internet
Author: User
Tags arithmetic static class true true wrapper

Because you know that the objects in the collection are object types when you learn the collection, you need to force the type conversion to the target type when you remove it (not necessary to use a generic collection), such as int a = (Integer) arraylist.get (0); and then we'll find out, Why cast to Integer instead of int? What is the difference between an int and an integer?

1. Difference between basic type and packing class

int is the basic type, directly depositing the value;

int i = 5;//allocates space directly on the stack, storing 5 of this value

The integer is the wrapper class of int, is a class, owns a method, such as:

Integer i = new integer (5);	I is the reference variable of the object, so allocate object space in heap memory, and store the address of the corresponding space in heap memory in the stack.

Java has eight basic data types, corresponding to eight kinds of packaging classes:

Short Short

int Integer

Long Long

Char Character

BYTE byte

float float

Boolean Boolean

Double Double

The value of the variable is stored in the stack, and the object is stored in the heap, which is more efficient than the stack, which is why Java retains the base type. The wrapper class creates objects that can be used by some useful methods provided by the API. More powerful.

2, automatic boxing and automatic unpacking

So let's analyze the process of integer i = 5;

Before jdk1.5, such code was wrong and had to be implemented through the integer i = new integer (5); After jdk1.5, Java provided the automatic boxing function, only integer i = 5; Such statements enable the basic data type to be passed to its wrapper class, and the JVM executes the Integer i = integer.valueof (5) for us; this is the Java automatic boxing.

Accordingly, the process of taking the basic data out of the corresponding packing class is to remove the box;

Integer i = 5;

Int J = i;//Such a process is automatic unpacking

source, in a word summed up the box and unboxing of the implementation process:

The boxing process is implemented by invoking the ValueOf method of the wrapper, and the unboxing process is implemented by invoking the Xxxvalue method of the wrapper. (XXX represents the corresponding basic data type)

Integer i = new integer (XXX) and integer i =xxx; the difference between these two ways:
1 The first method does not trigger the process of automatic boxing, and the second method triggers;
2 The difference between the efficiency of execution and the utilization of resources. The execution efficiency and resource footprint of the second approach are better than the first case in general (note that this is not absolute).

3, the source problem, interview questions: (reference http://www.cnblogs.com/dolphin0520/p/3780005.html)

A, here is a question that often arises, look at the following code:

public class Main {public
    static void Main (string[] args) {
         
        Boolean i1 = false;
        Boolean i2 = false;
        Boolean i3 = true;
        Boolean I4 = true;
         
        System.out.println (I1==I2);
        System.out.println (I3==I4);
    }
What is the output result?

True

False

The reasons for this result can be explained by the source code:

public static Integer valueof (int i) {
    if (i >= -128 && i <= integercache.high)//not set, IngegerCache.h IgH default is 127 return
        Integercache.cache[i + 128];
    else return the
        new Integer (i);
}

And the implementation of the Integercache class is:

private static class Integercache {static final int high;

        Static final Integer cache[];

            static {final int low =-128;
            High value May is configured by property int h = 127;
                if (integercachehighpropvalue!= null) {//Use Long.decode this to avoid invoking methods Require Integer ' s autoboxing cache to be initialized int i = Long.decode (Integercachehighpropvalu
                e). Intvalue ();
                i = Math.max (i, 127);
            Maximum array size is integer.max_value h = math.min (i, Integer.max_value--low);

            High = h;
            cache = new Integer[(high-low) + 1];
            int j = Low;
        for (int k = 0; k < cache.length; k++) cache[k] = new Integer (j + +); Private Integercache () {}} 
From these 2 pieces of code, you can see that when you create an integer object by using the ValueOf method, if the value is between [-128,127], it returns a reference to an object that already exists in Integercache.cache, otherwise a new integer object is created.
The I1 and I2 values in the above code are 100, so that the existing objects are taken directly from the cache, so i1 and I2 point to the same object, and i3 and I4 point to different objects respectively.


b, and if you change the four data types in the previous question to double or float, what is the result?

public static void Main (string[] args) {
         
        Double i1 = 100.0;
        Double i2 = 100.0;
        Double i3 = 200.0;
        Double i4 = 200.0;
         
        System.out.println (I1==I2);
        System.out.println (I3==I4);
    }
The answer is all false. For specific reasons, readers can look at the implementation of the valueof of the double class.

Here only explains why the valueof method of the double class uses a different implementation than the ValueOf method of the integer class. It's simple: the number of integer values within a range is limited, but the floating-point numbers are not.
Note that the implementations of the valueof methods for the classes of integers, short, Byte, Character, long are similar. The implementation of the valueof method of Double and float is similar.


C, to be a Boolean.

public class Main {public
    static void Main (string[] args) {
         
        Boolean i1 = false;
        Boolean i2 = false;
        Boolean i3 = true;
        Boolean I4 = true;
         
        System.out.println (I1==I2);
        System.out.println (I3==I4);
    }
The answer is all true.

As for why this result, see the Boolean class source will also be at a glance. The following is a specific implementation of the Boolean valueof method:

public static Boolean valueof (Boolean b) {return
        (b) True:false);
    }

And what is TRUE and false in it. 2 static member properties are defined in Boolean:

public static final Boolean TRUE = new Boolean (true);

    /** 
     * The <code>Boolean</code> object corresponding to the primitive 
     * value <code>false </code>. 
     *
    /public static final Boolean false = new Boolean (false);

At this point, you should understand why the results of the above output is true. D, the following code output what.

public class Main {public
    static void Main (string[] args) {
         
        Integer a = 1;
        Integer B = 2;
        Integer C = 3;
        Integer d = 3;
        Integer e = 321;
        Integer f = 321;
        Long g = 3L;
        Long h = 2L;
         
        System.out.println (C==d);
        System.out.println (e==f);
        System.out.println (c== (a+b));
        System.out.println (C.equals (a+b));
        System.out.println (g== (a+b));
        System.out.println (G.equals (a+b));
        System.out.println (G.equals (a+h));
    }
Don't look at the output, the reader will think about what the output of this piece of code is. What you should note here is that when the two operands of the "= =" operator are all references to the wrapper type, is whether the comparison points to the same object, and if one of the operands is an expression (that is, it contains an arithmetic operation), the comparison is a numeric value (that is, the process that triggers the automatic unboxing). In addition, for wrapper types, the Equals method does not convert to type. Understand these 2 points, the above output will be clear at a glance:

True
false True True
false
True
There is no doubt about the first and second output results. The third sentence because a+b contains arithmetic operations, the automatic unboxing process is triggered (the Intvalue method is called), so they compare the values for equality. And for C.equals (A+B) will trigger the automatic unpacking process, and then trigger the automatic boxing process, that is, A+b, will first call the Intvalue method, after the addition of the value of the operation, then call the Integer.valueof method, and then the equals comparison. The same is true for the latter, but note the result of the second and last output (if the value is of type int, the boxing procedure calls the integer.valueof; if it is a long type, the Long.valueof method of the boxing call).

Related Article

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.