Consolidate the basis of Java Series 2: Java automatically removable box hidden secrets

Automatic packing and unpacking (Detailed)

Static method valueOf (basic types): basic types -> package type ; as Integer.valueOf (10);
the method of Example xxxValue (): Packaging Type -> basic types ; such as Integer variables .intValue packaging ();

Automatic boxing and unboxing in the "pit"

When using auto-boxing and auto-unboxing, pay attention to some of the pitfalls to avoid these traps, we need to see what the various types of packaging source.
Integer source

public final class Integer extends Number implements Comparable<Integer> {
	private final int value;
	

/*这是Integer的构造方法,接受一个整型参数,Integer对象表示的int值,保存在value中*/
 public Integer(int value) {
        this.value = value;
 }
 
/*equals()方法判断的是:所代表的int型的值是否相等*/
 public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
}
 
/*返回这个Integer对象代表的int值,也就是保存在value中的值*/
 public int intValue() {
        return value;
 }
 
 /**
  * 首先会判断i是否在[IntegerCache.low,Integer.high]即[-128,127]之间
  * 如果是,直接返回Integer.cache中相应的元素
  * 否则,调用构造方法,创建一个新的Integer对象
  */
 public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
 }

/**
  * 静态内部类,缓存了从[low,high]对应的Integer对象
  * low -128这个值不会被改变
  * high 默认是127,可以改变,最大不超过:Integer.MAX_VALUE - (-low) -1
  * 									 即2的31次方-(128) -1
  * cache 保存从[low,high]对象的Integer对象
 */
 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;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            int i = parseInt(integerCacheHighPropValue);
            i = Math.max(i, 127); //这两行是为了一定确保h=127
            // Maximum array size is Integer.MAX_VALUE
            h = Math.min(i, Integer.MAX_VALUE - (-low) -1); //这两行是为了一定确保h=127
        }
        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() {}
}

Through the above analysis of the code, to give:

. 1) has a Integer instance field value, which preserves the value of type int Integer represented, and it is final, that is to say a complete constructed Integer object, it represents a value can no longer be changed.

2) Integer rewrite equals () method, which value by comparing the two Integer object to determine equality.

3) focusing on static inner classes IntegerCache, by class name can be found: it is used to cache data. It has an array of preservation which is continuous Integer object.
(a) low: represents the minimum value of the data buffer, is fixed -128.

(B) high: the data cache on behalf of the maximum value, it can be changed the default is 127. 127 is a high minimum, the maximum is Integer.MAX_VALUE - (- low) -1, high if exceeds this value, then the Cache [] more than the length of the Integer.MAX_VALUE, will overflow.

© cache []: which holds the [low, high] Integer object corresponding to a length of high-low + 1 (because of the elements 0, so to add 1).

4) call valueOf (inti) method first determines whether i [low, high] between, if so, the multiplexing Integer.cache [i-low]. For example, if Integer.valueOf (3), the direct return Integer.cache [131]; if i is not within this range, the call the constructor, to construct a new Integer object.

5) call intValue (), a direct return value for value.
It can be found by 3) and 4), by default, when using an automatic packing, the VM will be multiplexed between the Integer object [-128,127].

Here Insert Picture Description
The figure shows that
Integer default caching object between -128 to 127, an upper limit 127 may be changed by modifying the parameters JVM. It is arranged sun.misc.VM.getSavedProperty ( "java.lang.Integer.IntegerCache.high"); parameters
layman JAVA packaging and traps face questions

Further
int automatic unpacking and packing only in the range of -128 to 127, more than two of the integer range is to be determined == returns false.

For basic data types, == (double equal sign) is a value comparison, and for the type of packaging, == (double equal sign) is to compare the memory address of the object 2.

View source was found
1.Integer types of cache [-128,127] objects. The upper limit can be changed by cache configuration JVM
2.Byte, cache length Short, Long buffer 256 is [-128,127]
3. The length of the cache 128 is a cache Character [0,127]
4 and Float, Double no cache (probably because the float is not that bad accurate comparison of the number of cache for equality)

In particular, need special attention that will use the cache, new methods will not use the cache only valueOf method to construct the object!

Encountered pit

1. Compare the number in [-127,128] within range but why == false returns and returns equal to true?
Here Insert Picture DescriptionHere Insert Picture Description
1 is because when using == for primitive types (int) is for comparison value for reference types it is more of a reference that is an address; it is a cache of a new out is not the same as a natural
2 and equals default is a reference to compare , but a lot of class overrides the equals method , such as String, Integer and so it becomes a comparison value , so this case is the value equals comparisons are equal.
Do you really know the difference between == and the equals of it?
plus: compare that to the number two Integer exceeds the range, then the cache rather than a new comparison is == or equals false and true (because rewrite the equals method)
Here Insert Picture Description
Here Insert Picture Description
Further Whether
1. Exceeding cache
2. or out of the new package class
in the comparison are substantially in accordance with the class (int) values for direct comparison
Here Insert Picture Description
Here Insert Picture Description
because the package type == basic type, packing type automatic unpacking;
Note that: when == arithmetic not encountered, not automatically unpacking; only basic types of automatic packing corresponding type of packaging, in the content code of the last described. '
I.e. d above automatic packaging according to Integer then said before == will first determine whether it is true return with reference to a
series of problems face questions regarding a recording buffer Integer range (-128 to 127) caused by

Basic data storage type

The method of present variable stack local variable table
object class instantiated presence heap
basic data types in the type of packaging may be constant pool lookup values corresponding to the object, the object is automatically created can not find the value in the constant pool
JDK1. 7, the pile is put into the constant pool .

Reference material

Published 81 original articles · won praise 19 · views 3614

Guess you like

Origin blog.csdn.net/c22cxz/article/details/104719330