Interviewer: the difference between the brothers, talk about the basic types and type of packaging it

Six years ago, I returned from Luoyang, Suzhou, holding a "returnees" mentality, cast a lot of resumes, but also "interviewed" a lot of the interviewer, but only twenty-three I am satisfied. One of them called the horse, still live in my cell phone address book. He then threw a smashing my face questions ignorant: Tell me about the difference between the basic types and type of packaging it.

I was twenty-three, positive youth, engaged in years of experience in Java programming has N (N <4), think of all the interview questions can be fluent, the results did not think ah, were "difficulties" - the original Luoyang Internet this desert there are technical experts ah. In retrospect, his face unconsciously thrown a shame blush: mainly himself was too dishes. Anyway, it's time to write an article about the difference between the basic types and analyze types of packaging.

Each basic types of Java corresponds to a type of packaging, such as packaging int type Integer, double packaging type Double. The difference between the basic types and types of packaging are the following four points.

01, the type of packaging can be null, but not the basic types

Do not underestimate this difference, so that it can be applied to the POJO package type, and is not basic types.

POJO What is it? Explain a little here.

POJO English stands Plain Ordinary Java Object, translate what is, no simple rule of Java objects, only the attribute fields and getter and setter methods, examples are as follows.

class Writer {
    private Integer age;
    private String name;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

POJO and similar, as well as data transfer objects DTO (Data Transfer Object, refers to an object for data transmission between the service layer and the presentation layer), the view object VO (View Object, a page of data encapsulated), persistent object PO (Persistant Object, Java objects can be seen in the database table mapping).

Why POJO properties must use the type of packaging it?

There are detailed instructions on the "Ali Baba Java Development Manual", we read aloud about the (preparation, starting).

Database results may be null, if you use basic types of words, due to the auto-unboxing (the type of packaging into basic types, such as Integer object to convert to an int value), it will throw NullPointerExceptionexceptions.

02, the package can be used for generic type, base type and not

Generics can not use basic types, because it will compile error when using the basic types.

List<int> list = new ArrayList<>(); // 提示 Syntax error, insert "Dimensions" to complete ReferenceType
List<Integer> list = new ArrayList<>();

why? Because generics at compile time type will be erased, finally leaving only the original type, and only primitive type Object class and its subclasses - basic type is a special case.

03, the basic type is more efficient than the type of packaging

Substantially directly stored in the stack type specific values, and the type of packaging is stored is a reference to the heap.

 

 

Obviously, compared to the basic terms of the type, packaging type need to take up more memory space. If there is no basic types of words, often used for this type of numerical data is, each time by a new type of packaging is very cumbersome.

03, the two values ​​may be the same type of packaging, but do not equal

Two-wrapped may be the same, but they are not equal - this sentence how to understand it? Look at a section of the code clearly.

Integer chenmo = new Integer(10);
Integer wanger = new Integer(10);

System.out.println(chenmo == wanger); // false
System.out.println(chenmo.equals(wanger )); // true

When two package types using the "==" is judged, it is determined that the address to which it points are equal. chenmo and wanger two variables using the new keyword, causing them to output in a false "==" when.

And the chenmo.equals(wanger)output result is true, because the equals method to compare the internal int two values are equal. Source follows.

private final int value;

public int intValue() {
    return value;
}
public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

Look, although the value chenmo and wanger are 10, but they are not equal. In other words: the "==" operator is applied to compare the package type, the result is likely to be expected and does not match .

04, and automatic unboxing autoboxing

Now that you have the basic types and package types, certainly there are times when you want to switch between them. Converted into basic type of process is called packing type packaging (boxing). Conversely, to convert the basic type of package type process is called unpacking (unboxing).

Before Java SE5, developers should manually with the goods, for example:

Integer chenmo = new Integer(10);  // 手动装箱
int wanger = chenmo.intValue();  // 手动拆箱

Java SE5 order to reduce the work of developers, provides automatic packing and unpacking of automatic functions.

Integer chenmo  = 10;  // 自动装箱
int wanger = chenmo;     // 自动拆箱

The above code uses JAD decompiled results as follows:

Integer chenmo = Integer.valueOf(10);
int wanger = chenmo.intValue();

That is, by automatic packing Integer.valueOf()done; unboxing is through automatic Integer.intValue()done. Once you understand the principle, let's look at a horse face questions then give me out.

// 1)基本类型和包装类型
int a = 100;
Integer b = 100;
System.out.println(a == b);

// 2)两个包装类型
Integer c = 100;
Integer d = 100;
System.out.println(c == d);

// 3)
c = 200;
d = 200;
System.out.println(c == d);

What's the answer? You have raised their hands to answer it? Correct answers reward a small red flower Oh.

First code, and type of packaging basic types == comparison, this time will be automatically unpacking b, and a direct comparison value, the result is true.

The second paragraph of the code, two package types are assigned to 100, this time will be auto-boxing, what would be the result of == is it?

Our previous conclusions are: the "==" operator is used when comparing the type of packaging, the result is likely to be incompatible and expected. That result is false? But this time the result is true, is not feeling very unexpected?

The third paragraph of the code, two re-package type is assigned to 200, this time will still be auto-boxing, what would be the result of == is it?

After the second paragraph of code at a disadvantage, is not it a bit skeptical life, and this result is true or false it? Throw a coin, ha ha. Let me tell you the results of it, false.

why? why? why?

Things to this point, have resorted to the killer - source code analysis of it.

Before we already know, through the automatic packing Integer.valueOf()done, then we take a look at the source of this approach it.

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

Implying that IntegerCache in trouble? you guessed right!

private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        int i = parseInt(integerCacheHighPropValue);
        i = Math.max(i, 127);
        h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }
}

Roughly cast a glance at this code you'll all understand. Number between -128 and 127 will be taken from IntegerCache then compare, so the second segment of code (100 in within this range) the result is true, and the third segment of code (200 is not within this range, the new out two Integer objects) result is false.

After reading the above analysis, I hope you remember this: When the need for automatic packing, if the numbers between -128 to 127, will directly use objects in the cache, rather than re-create an object .

Automatically with the goods is a nice feature, saving the effort of our developers, but it can cause problems, such as the following code, performance is poor.

long t1 = System.currentTimeMillis();
Long sum = 0L;
for (int i = 0; i < Integer.MAX_VALUE;i++) {
    sum += i;
}
long t2 = System.currentTimeMillis();        
System.out.println(t2-t1);

Since the sum would be declared type of packaging is not basic types Long long, so sum += ia lot of operation of the entry box (sum unpacking the first sum and i, and then assigned to sum packing), leading to completion of running this code takes a full 2986 ms time; if the sum into the elementary type long, only time 554 msec, like the order of a completely ah.

 

 

Guess you like

Origin www.cnblogs.com/qing-gee/p/11605791.html