jdk1.5后增加了自动拆箱和自动装箱特性。java的八种 byte,short,int,long,float,double,char,boolean基本类型和各自对应的包装类型的相互转化。
装箱指的是 int类型 变为 Integer实例对象,拆箱指的是 Integer实例 变为 int类型。
java.lang包下的类Integer。作为int基本类型的封装类。有以下特点。
一、
Integer a = 100;
Integer b = 100;
Integer c = 1000;
Integer d = 1000;
System.out.println(a == b);
System.out.println(c==d)
输出结果是:true false
分析:
(1)Integer a = 100;会自动掉用Integer的 valueOf(int i)方法进行自动装箱。当值i >=-128 && i < 127 时会调用已经初始化好的缓存中的Integer实例。
所以 System.out.println(a == b) 中 a、b指向相同Integer对象的实例
(2)Integer b = 1000, 虽然也会掉用Integer中valueOf(int i)方法进行自动装箱。但是值得范围不在缓存中。所以c 、d返回的是不同Integer对象的实例。
所以 System.out.println(c == d) 输出的结果为false
备注:jdk之所以这么设计是因为小数字[-128,127)访问频率比较高,放在缓存中提高Integer类的性能和效率。
Jdk中Integer类的源码如下:
1 /** 2 * Returns a <tt>Integer</tt> instance representing the specified 3 * <tt>int</tt> value. 4 * If a new <tt>Integer</tt> instance is not required, this method 5 * should generally be used in preference to the constructor 6 * {@link #Integer(int)}, as this method is likely to yield 7 * significantly better space and time performance by caching 8 * frequently requested values. 9 * 10 * @param i an <code>int</code> value. 11 * @return a <tt>Integer</tt> instance representing <tt>i</tt>. 12 * @since 1.5 13 */ 14 public static Integer valueOf(int i) { 15 if(i >= -128 && i <= IntegerCache.high) 16 return IntegerCache.cache[i + 128]; 17 else 18 return new Integer(i); 19 }
1 private static class IntegerCache { 2 static final int high; 3 static final Integer cache[]; 4 5 static { 6 final int low = -128; 7 8 // high value may be configured by property 9 int h = 127; 10 if (integerCacheHighPropValue != null) { 11 // Use Long.decode here to avoid invoking methods that 12 // require Integer's autoboxing cache to be initialized 13 int i = Long.decode(integerCacheHighPropValue).intValue(); 14 i = Math.max(i, 127); 15 // Maximum array size is Integer.MAX_VALUE 16 h = Math.min(i, Integer.MAX_VALUE - -low); 17 } 18 high = h; 19 20 cache = new Integer[(high - low) + 1]; 21 int j = low; 22 for(int k = 0; k < cache.length; k++) 23 cache[k] = new Integer(j++); 24 } 25 26 private IntegerCache() {} 27 }
读了源码可以发现点,缓存数组的范围大小low是确定的-128,但是high可以通过jvm参数自行配置。
二、
Integer a = new Integer(1000);
Int b = 1000;
System.out.println(a == b);
输出结果为true;
分析:
当a 与 b进行 == 比较时,会将a自动拆箱为基本类型1000,所以结果为true;