关于Integer与int的装箱拆箱

Object可以接受所有的引用数据类型,那么基本数据类型怎么办呢?所以就产生了包装类(将基本数据类型封装到类中)

Integer就是int的包装类,int初值为0,Integer初值为null,

装箱:将基本数据类型变为包装类对象,利用每一个包装类提供的构造方法是向装箱处理

拆箱:将包装类中包装的基本数据类型取出

装箱:int---->Integer

valueOf()是装箱方法之一 

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  }

 为什么 i==j 是true?

因为 第3行是将一个int类型用valueOf()方法装箱成一个Integer类型,第4行是将int对象赋值给Integer类型,此时int对象会进行自动装箱操作,调用Integer的静态方法valueOf(int i),传入一个int对象,返回一个Integer对象,所以3,4两行两个赋值方法是没有区别的

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 }

为什么 x == y 是false?

看到这里大家一定很奇怪 x == y 怎么就是false,equals有事true,这个还要从Integer.ValueOf()的源码看起

/**
 * 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);
}

注意看代码,if语句里面,IntegerCache.low和IntegerCache.high 分别为-128,127,由代码看出如果传入的int值在-128到127之间,则调用了一个IntegerCache类,否则new了一个新的Integer对象,我们都知道new出来的对象位于堆中,new多少次就有多少个不同的对象,但是IntegerCache是什么呢?

/**
 * 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() {}
}

由源码看出IntegerCache这里面封装了一个Integer类型的数组(static final Integer cache[]; // 缓存了一个Integer类型的数组) 

存放-128到127之间的Integer类型的对象,第一次使用进行初始化(cache[k] = new Integer(j++); // 初始化数组)

所以Integer.valueOf(int i)方法,在传入的i的值不在-128-127之间时,便new出一个新的Integer对象,,如果范围在-128-127之间则直接从IntegerCache缓存中取出存放的对应Integer对象

返回来再看上面i和j,x和y的比较,因为i=127,在-128-127这个范围内,所以int类型的127在进行装箱操作的时候调用ValueOf()方法时,取出的是IntegerCache中缓存的Integer对象,所以不管多少个127,只要调用ValueOf()方法,返回的都是一个Integer对象,用"=="比较返回true,内存地址也只有一个

x=128,不在-128-127这个范围内,所以每次调用ValueOf()方法,都会产生一个独一无二的Integer对象,所以用"=="比较返回false,但是因为两个都是引用对象,用equals()方法则会返回true,因为x,y的字面值均为128

拆箱:Integer--->int

intValue是六大拆箱方法之一

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 }

为什么 i == j 是true,j == z 是false?

因为在Integer对象和int对象做比较时,Integer j对象会调用intValue()方法返回一个int对象,也就是自动拆箱操作,返回的这个int对象再与int i 对象进行比较,此时两个做比较的对象都是int对象,都为基本类型,所以"=="直接比较值是否相等,所以第3,4行赋值方法是一样的,比较结果也就是true

 第7行将Integer赋值为null(这里要注意的事int类型不能赋值为null,默认为0,而Integer默认为null),与Integer J 对象进行比较,空和10比较结果就为false

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 }

 第8行:因为在编译的时候将Integer k 编译成Integer.valueOf(10),而Integer z又是重新new了一个Integer对象,所以结果为false

第9行:因为Integer j 调用intvalue()方法自动拆箱为int类型,所以结果为true

第10行:j和z都是重新各自new了Integer对象,在堆中产生了两个对象,所以不相等,结果为false

第11行:两个都是Integer对象,调用intvalue()方法自动拆箱变为两个int类型,相等,所以结果true

总结

(1)无论如何,Integer和new Integer不会相等,不会经历拆箱过程,j的引用指向堆,k有专门存放它的内存,地址不一样,所以不相等

(2)如果两个都是非new出来的Integer,如果数在-128-127之间,则为true,否则为false

(3)如果两个都是new出来的,都为false

(4)int和Integer(无论new与否),都为true,因为Integer会自动拆箱为int再去比

猜你喜欢

转载自blog.csdn.net/weixin_43224539/article/details/91354830
今日推荐