About Integer int packing and unpacking

Object can accept all types of reference data, then how to do basic data types? So it arises packaging (encapsulating the basic data types to the class)

Integer wrapper class is int, int initial value of 0, Integer initial value is null,

Packing : The basic data types becomes packaging objects, each using a wrapper class constructor is provided to the packing process

Unpacking : The packaging wrapper class basic data types removed

Packing: int ----> Integer

valueOf () method is one of the packing 

1  public class Test0609 {
2      public static void main(String[] args) {
3          Integer i = Integer.valueOf(127);
4          int j = 127;
5          System.out.println(i == j); //true
6     }
7  }

 Why i == j is true?

Because line 3 is the type with an int valueOf () method of packing into a type Integer, line 4 is assigned to an object of type Integer int, int this case the object will be automatically packing operation , call the static method of Integer valueOf (I int), int a passing object, and returns an Integer object, two rows of two 3,4 assignment method is no difference

1public class Packing {
2    public static void main(String[] args) {
3        Integer x = Integer.valueOf(128);
4        Integer y = 128;
5        System.out.println(x == y);  //false
6        System.out.println(x.equals(y)); //true
7    }
8 }

Why x == y is false?

Here we must be very strange to see how x == y is false, equals something true, this would also like to see from the Integer.ValueOf () source code

/**
 * Returns an {@code Integer} instance representing the specified
 * {@code int} value.  If a new {@code Integer} instance is not
 * required, this method should generally be used in preference to
 * the constructor {@link #Integer(int)}, as this method is likely
 * to yield significantly better space and time performance by
 * caching frequently requested values.
 *
 * This method will always cache values in the range -128 to 127,
 * inclusive, and may cache other values outside of this range.
 *
 * @param  i an {@code int} value.
 * @return an {@code Integer} instance representing {@code i}.
 * @since  1.5
 */
public static Integer valueOf(int i) {
	if (i >= IntegerCache.low && i <= IntegerCache.high)
		return IntegerCache.cache[i + (-IntegerCache.low)];
	return new Integer(i);
}

Note the codes, which IF statement, IntegerCache.low IntegerCache.high and -128,127 respectively, by the code to see if the incoming int value between -128 and 127, is called a IntegerCache class, a new or new Integer object, we all know that new object is located out of the heap, how many there are that many different objects new, but what IntegerCache is it?

/**
 * Cache to support the object identity semantics of autoboxing for values between
 * -128 and 127 (inclusive) as required by JLS.
 *
 * The cache is initialized on first usage.  // 第一次使用时进行初始化
 * The size of the cache may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
 * // 数组的大小可以通过控制虚拟机的-XX:AutoBoxCacheMax=<size>参数来设置。
 */
private static class IntegerCache {
	static final int low = -128;
	static final int high;
	static final Integer cache[]; // 缓存了一个Integer类型的数组
 
	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) {
			try {
				int i = parseInt(integerCacheHighPropValue);
				i = Math.max(i, 127);
				// Maximum array size is Integer.MAX_VALUE
				h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
			} catch( NumberFormatException nfe) {
				// If the property cannot be parsed into an int, ignore it.
			}
		}
		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;
	}
 
	private IntegerCache() {}
}

Seen by the source IntegerCache there is a package type Integer arrays (static final Integer cache []; // cache array of a type Integer) 

Type Integer object stored between -128 to 127 , used to initialize the first (cache [k] = new Integerinitialize an array)

Therefore Integer.valueOf (int i) method, the value of i is passed is between -128-127 not, then a new new Integer object, that if the range between -128-127 directly from the cache IntegerCache remove the Integer object stored in the corresponding

I look back to compare above and j, x and y, since i = 127, -128-127 within this range, it is invoked during ValueOf () method when the packing operation type int 127, taken IntegerCache is cached Integer object, so no matter how many 127, just call ValueOf () method that returns are a Integer object, use the "==" comparison returns true, and only a memory address

x = 128, -128-127 not within this range , it ValueOf each call () method will generate a unique Integer object, with "==" comparison returns false, but because the two reference objects are, by equals () method will return true, because the x, y are literals 128

Unpacking: Integer ---> int

intValue is one of the six methods unboxing

1 public int intValue() {
2	 return value;
3 }
1public class Unpack {
2    public static void main(String[] args) {
3        int i =10;
4        Integer j = 10;
5        System.out.println(i == j); //true
6
7        Integer z = null;
8        System.out.println(j == z); //false
9    }
10 }

Why i == j is true, j == z is false?

Because in the int Integer object and compare objects, J Integer object calls intValue () method returns an int object is automatically unpacking operation , and then return the objects int int i is compared with the target, and the two do objects of comparison are int objects are the basic types, so "==" direct comparison values are equal, the third and fourth line assignment method is the same, the comparison is true

 Line 7 Integer assigned to null ( Here we must pay attention to things int type can not be assigned to null, the default is 0, and Integer default is null ), compare, compare results with the air and 10 on the object to false Integer J

1public class Test0609 {
2   public static void main(String[] args) {
3        int i =10;
4        Integer k = 10;
5        Integer p = 10;
6        Integer j = new Integer(10); //装箱
7        Integer z = new Integer(10);
8        System.out.println(k == j); //false
9        System.out.println(i == j); //true
10       System.out.println(j == z);//false
11       System.out.println(p == k); //true
12
13    }
14 }

 Line 8: at compile time because the Integer K compiled into Integer.valueOf (10), while new Integer Z is an Integer object again, so the result is false

Line 9: Integer j call because intValue () method for automatically unpacking to an int, so the result is true

Line 10: j and z are each again a new Integer object, the two objects in the heap is generated, it is not equal, the result is false

Line 11: two are Integer object, call intValue () method for automatically unpacking two int type becomes equal, so the result true

to sum up

(1) In any case, Integer, and new Integer will not equal, will not go through the process of unpacking, j reference point heap, k specialized store it in the memory, the address is different, so are not equal

(2) If both are non-new out of the Integer, if the number is between -128-127, true, or not, false

(3) If both are out of the new, are false

(4) int and Integer (whether new or not), are true, because Integer will automatically go unboxing to int ratio

Guess you like

Origin blog.csdn.net/weixin_43224539/article/details/91354830