有一个自动拆箱与装箱引出的问题:
Integer i = 126;
Integer j = 126;
System.out.println("i==j="+(i==j));
System.out.println("i.equals(j)="+i.equals(j));
Integer m = 128;
Integer n = 128;
System.out.println("m==n="+(m==n));
System.out.println("m.equals(n)="+m.equals(n));
结果是:
i==j=true i.equals(j)=true m==n=false m.equals(n)=true
执行Integer i = 126,实际是系统为我们执行了Integer i= Integer.valueOf(126);在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); }
所以数值在-128~127范围内的,Integer.valueOf(int i) 返回的是缓存的Integer对象(并不是新建对象); 其他的是返回一个新建出来的Integer对象。
自动拆箱(unboxing),也就是将对象中的基本数据从对象中自动取出